29 окт. 2024 г.

Python script ping and log

import subprocess, time
while True:
    result = None
    try:
        result = subprocess.check_output(['ping','-w', '1', '-c', '1', '-n', '-q' ,'192.168.0.1'])
        result = result.decode("utf-8").split('/')
        result = float(result[4])
    except:
        with open("mon.log", "a") as myfile:
            myfile.write(time.strftime('%X %x %Z')+' Ping error.\n')
        myfile.close()
    print result
    if result > 5 :
        with open("mon.log", "a") as myfile:
            myfile.write(time.strftime('%X %x %Z')+' '+str(result)+'\n')
        myfile.close()
    time.sleep(1)