1. Ping Connectivity Test
1 #!/usr/bin/env python2 #-*-coding:utf-8-*-3 ImportOs,sys,re4 Importsubprocess5 6 defNetcheck (IP):7 Try:8p = subprocess. Popen (["ping-c 1-w 1"+ ip],stdout=subprocess. Pipe,stderr=subprocess. Pipe,shell=True)9out=P.stdout.read ()Ten #Err=p.stderr.read () OneRegex=re.compile ('100% Packet Loss') A #Print out - #Print Regex - #Print Err the ifLen (Regex.findall (out)) = =0: - PrintIP +': Host up' - return ' up' - Else: + PrintIP +': Host down' - return ' Down' + except: A Print 'Netcheck Work error!' at return 'ERR‘
ip1= "2.3.2.2"
domain1= "Www.baidu.com"
Netcheck (IP1)
Netcheck (domain1)
Or: The connection returns 0, does not pass return 512
1>>> Ret1=os.system ('ping-c 2-w 1 114.114.114.14')2PING 114.114.114.14 (114.114.114.14): 56Data bytes3Request Timeout foricmp_seq 04 5---114.114.114.14 ping statistics---62 packets transmitted, 0 packets received, 100%Packet Loss7>>>Ret18 +9>>> Ret1=os.system ('ping-c 2-w 1 114.114.114.114')TenPING 114.114.114.114 (114.114.114.114): 56Data bytes One A---114.114.114.114 ping statistics--- -2 packets transmitted, 2 packets received, 0.0% packet loss, 2packets out of wait time -Round-trip Min/avg/max/stddev = 27.535/31.029/34.523/3.494Ms the>>>Ret1 - 0 ->>>
2. HTTP (s) connectivity test
#!/usr/bin/env python
#-*-coding:utf-8-*-
Import urllib2
1 defhttp_validate (target_url):2 Try:3 Urllib2.urlopen (target_host)4 returnTrue5 except:6 returnFalse7 8 9URL1 ='https://www.baidu.com'TenURL2 ='http://www.baudi.com' One A ifhttp_validate (URL1): - Print "up to" - Else: the Print "not reached" - - ifhttp_validate (URL2): - Print "up to" + Else: - Print "not reached"
Reference:
1, http://dgd2010.blog.51cto.com/1539422/1865925
2, http://blog.csdn.net/wyzxg/article/details/40048445
Python's approach to testing network accessibility