1. 程式人生 > >python測試網絡可達性的方法

python測試網絡可達性的方法

get min 2.3 all net class logs import cnblogs

1、ping連通性測試

 1 #!/usr/bin/env python
 2 #-*- coding: utf-8 -*-
 3 import os,sys,re
 4 import subprocess
 5 
 6 def NetCheck(ip):
 7    try:
 8     p = subprocess.Popen(["ping -c 1 -W 1 "+ ip],stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
 9     out=p.stdout.read()
10     #err=p.stderr.read()
11 regex=re.compile(100% packet loss) 12 #print out 13 #print regex 14 #print err 15 if len(regex.findall(out)) == 0: 16 print ip + : host up 17 return UP 18 else: 19 print ip + : host down 20 return DOWN 21 except: 22 print NetCheck work error!
23 return ERR

ip1="2.3.2.2"
domain1="www.baidu.com"
NetCheck(ip1)
NetCheck(domain1)

或者:連通返回0,不通返回512

 1 >>> ret1=os.system(ping -c 2 -W 1 114.114.114.14)
 2 PING 114.114.114.14 (114.114.114.14): 56 data bytes
 3 Request timeout for icmp_seq 0
 4 
 5 --- 114.114.114.14 ping statistics ---
 6
2 packets transmitted, 0 packets received, 100.0% packet loss 7 >>> ret1 8 512 9 >>> ret1=os.system(ping -c 2 -W 1 114.114.114.114) 10 PING 114.114.114.114 (114.114.114.114): 56 data bytes 11 12 --- 114.114.114.114 ping statistics --- 13 2 packets transmitted, 2 packets received, 0.0% packet loss, 2 packets out of wait time 14 round-trip min/avg/max/stddev = 27.535/31.029/34.523/3.494 ms 15 >>> ret1 16 0 17 >>>

2、http(s)連通性測試

#!/usr/bin/env python  
#-*- coding: utf-8 -*-
import urllib2

1
def http_validate(target_url): 2 try: 3 urllib2.urlopen(target_host) 4 return True 5 except: 6 return False 7 8 9 url1 = https://www.baidu.com 10 url2 = http://www.baudi.com 11 12 if http_validate(url1): 13 print "可達" 14 else: 15 print "不可達" 16 17 if http_validate(url2): 18 print "可達" 19 else: 20 print "不可達"

參考:

1、http://dgd2010.blog.51cto.com/1539422/1865925

2、http://blog.csdn.net/wyzxg/article/details/40048445

python測試網絡可達性的方法