0

I'm trying to ping an IP and insert the entire CMD output into a text file using Python3. getIP() returns a list of IPs to ping. I do not need to append each output of every ping because the file is meant to be temporary and overwritten with each ping. My ultimate goal is to parse the avg rtt from the ping output.

IP = getIP() 
with open('out.txt', 'w') as f:
    for ip in IP:
        s = str(os.system('ping %s -c 4' % ip))
        f.write(s)
        time.sleep(3)

Thanks

yuenster
  • 15
  • 1
  • 3
  • It's **really** better if you don't use `os.system()` here. Make it `subprocess.run(['ping', ip, '-c', '4'], stdout=f)` and there you are, and without security holes if someone can inject `$(rm -rf ~)` into your list of hosts to ping. – Charles Duffy Mar 04 '20 at 01:16
  • ...but that said, why write to a file at all instead of just reading the text straight to a variable? See f/e the `capture_output=True` option in `subprocess.run()`, or for older versions of Python, the `communicate()` method on `subprocess.Popen` objects. – Charles Duffy Mar 04 '20 at 01:16
  • (btw -- *don't* use `shell=True` on any `subprocess`-module method or constructor, or else you get those security holes back! Any answer that advises it should be used with caution). – Charles Duffy Mar 04 '20 at 01:25

0 Answers0