Borrowed from the predecessors of the blog, and then added a lot of things.
which uses the Subprocess module.
>>> Import subprocess
>>> p = subprocess. Popen (' Df-h ', stdin=subprocess. Pipe,stdout=subprocess. Pipe,stderr=subprocess. Pipe,shell=true)
#获取命令执行结果的返回码, through the Wait () function
>>> p.wait ()
0
#获取命令输出结果 (standard output), via the Read () method
>>> P.stdout.read ()
' Filesystem Size used Avail use% mounted on\n/dev/sda1 18G 11G 5.8G 65%/\ntmpfs 495M 0 495M 0%/dev/shm\n '
#获取命令错误输出结果, through the Read () method
>>> P.stderr.read ()
''
#为空, indicating no error output
#获取错误输出
<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\n '
Other ways to get error output are: Read (), ReadLine (), ReadLines (), close (), write (), and Writelines ().
#!/usr/bin/env python
#_ *_ Coding:utf8 _*_
# by Lijiajun
Import Re,subprocess,os,sys
net_region= ' 192.168.3 '
Print ("#########################################################")
Print ("#此脚本主要基于ping, test for a network segment used IP and unused 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 "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 "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 ("\033[1;32;40m%s is up \033[0m")% (IP)
F=file ('/tmp/alive_ip.txt ', ' a ')
F.write ('%s\n '%ip)
F.close ()
Alive_ip=alive_ip+1
Print "Alive_ip count is%d"% alive_ip
Return ALIVE_IP
Else
Print "\033[31m%s is down\033[0m"% (IP)
F=file ('/tmp/dead_ip.txt ', ' a ')
F.write ('%s\n '%ip)
F.close ()
Dead_ip=dead_ip+1
Print "Dead_ip count is%d"% dead_ip
Return DEAD_IP
If name== "main":
#f =file ('/tmp/iplist.txt ')
For I in Range (1,255):
ip= '%s.%s '% (net_region,i)
Print IP
Check_alive (ip,1,1)
Print ("")
Print "Final dead_ip count is%d"% dead_ip
Print "Final alived_ip count is%d"% alive_ip