其中用到了subprocess模块
>>> import subprocess
>>> p = subprocess.Popen('df -h',stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
#获取命令执行结果的返回码,通过wait()函数
>>> p.wait()
0
#获取命令输出结果(标准输出),通过read()方法
>>> p.stdout.read()
'Filesystem Size Used Avail Use% Mounted on /dev/sda1 18G 11G 5.8G 65% / tmpfs 495M 0 495M 0% /dev/shm '
#获取命令错误输出结果,通过read()方法
>>> p.stderr.read()
''
#为空,说明没有错误输出
#获取错误输出
<subprocess.Popen object at 0x7f267528dbd0>
>>> p = subprocess.Popen('ls /etc/password',stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,close_fds=True)
>>> p.stderr.read()
'ls: cannot access /etc/password: No such file or directory '
@获取错误输出的其他方法还有:read(),readline(),readlines(),close(),write()和writelines()等.
#!/usr/bin/env python
#_*_ coding:utf8 _*_
# by lijiajun
import re,subprocess,os,sys
net_region='192.168.3'
print("#########################################################")
print("#此脚本主要基于ping,测试某网段已用ip和未使用的ip #")
print("#分别将其保存到/tmp/alive_ip.txt #")
print("#以及/tmp/dead_ip.txt #")
print("#########################################################")
print(" ")
if os.path.isfile("/tmp/alive_ip.txt"):
os.popen("mv /tmp/alive_ip.txt /tmp/alive_ip.txt.old")
print "you can see the used ip in this file : /tmp/alive_ip.txt"
if os.path.isfile("/tmp/dead_ip.txt"):
os.popen("mv /tmp/dead_ip.txt /tmp/dead_ip.txt.old")
print "you can see the unused ip in this file : /tmp/dead_ip.txt"
print(" ")
dead_ip=0
alive_ip=0
def check_alive(ip,count,timeout):
global alive_ip
global dead_ip
cmd='ping -c %d -w %d %s' % (count,timeout,ip)
p=subprocess.Popen(cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
result=p.stdout.read()
regx=re.findall('100% packet loss',result)
if len(regx)==0:
print("