Skip to content

Instantly share code, notes, and snippets.

@informationsea
Created July 30, 2024 01:32
Show Gist options
  • Save informationsea/35af3ec51b3539e3c2ba20f52f7cdaa8 to your computer and use it in GitHub Desktop.
Save informationsea/35af3ec51b3539e3c2ba20f52f7cdaa8 to your computer and use it in GitHub Desktop.
Watch ping
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import subprocess
import datetime
def _main():
parser = argparse.ArgumentParser(description="Ping watch")
parser.add_argument('host')
parser.add_argument('-l', '--logfile', type=argparse.FileType('at'))
options = parser.parse_args()
options.logfile.write(
"=============== Pinging {} ===============\n".format(options.host))
p = subprocess.Popen(['ping', options.host],
stdout=subprocess.PIPE, encoding='utf-8')
while True:
try:
line = p.stdout.readline()
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if line:
print(now, line, end='')
options.logfile.write(now + " " + line)
else:
break
except KeyboardInterrupt:
p.terminate()
break
if __name__ == '__main__':
_main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment