'''
2017 - python3 script starting template.
* Parse args
* Subprocess
* re regular expressions.
'''
#####-----#####------#####-----#####-----#####
#####-----#####------#####-----#####-----#####
#####-----#####------#####-----#####-----#####
import re
import time
import subprocess
def ping(hosts=[ "8.8.8.8" ],debug=1):
p = dict() # {} # ip -> process
for n in hosts: # start ping processes
ip = "%s" % n
p[ip] = subprocess.Popen(['ping', '-q' , '-n', '-w5', '-c1', ip], stdout=subprocess.PIPE,stderr=subprocess.STDOUT,shell=False,)
#NOTE: you could set stderr=subprocess.STDOUT to ignore stderr also
if debug:
time.sleep(0.2)
print("Start ping display ...")
while p:
time.sleep(0.2) #Slowdown looping
for ip, proc in p.items():
if proc.poll() is not None: # ping finished
del p[ip] # remove from the process list
if proc.returncode == 0:
print('%s active' % ip)
elif proc.returncode == 1:
print('%s no response' % ip)
else:
print('%s error' % ip)
# rtt min/avg/max/mdev = 22.293/22.293/22.293/0.000 ms
out=proc.communicate()[0]
if debug>2: print("out=",out)
search = re.search(b'rtt min/avg/max/mdev = (.*)/(.*)/(.*)/(.*) ms',
out, re.M|re.I)
if search:
ping_rtt = search.group(2).decode('utf-8')
print( "OK " + str(ip) + " rtt= "+ ping_rtt )
break
#print("skip ")
#####-----#####------#####-----#####-----#####
def pingOk(sHost):
try:
output = subprocess.check_output("ping -{} 1 {}".format('c', sHost), shell=True)
except Exception as e:
return False
return True
#####-----#####------#####-----#####-----#####
def run(debug=0):
# with stderr=subprocess.STDOUT, stdout and stderr will be combined
# run(..., check=True, stdout=PIPE).stdout
stdout = subprocess.run(["ls", "-l", "/dev"], stdout=subprocess.PIPE).stdout
if debug: print("debug: run: ",stdout)
#####-----#####------#####-----#####-----#####
import argparse
def getArgs(debug=0):
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
if debug: print("debug: args:",args.accumulate(args.integers))
return args
#####-----#####------#####-----#####-----#####
def main():
args = getArgs(debug=0)
print()
print( pingOk("8.8.8.8") )
#run(debug=1)
ping(["8.8.8.8", "4.2.2.2.4.4" , "vigor.nz" , "3.5.7.9"])
#####-----#####------#####-----#####-----#####
if __name__ == "__main__":
# execute only if run as a script
main()
#####-----#####------#####-----#####-----#####...
