0

What I tried as below which giving me error message.

What I want: I actually want to ping N number of servers and traceroute it and result should be saved in a text file. No matter if it store in any other format too but it should be easy to understand and read.

Issue: Error related to Popen is not getting resolved however if you aware of any other method, please welcome to that too. Please help. Thanks in advance.

Note: I am using Windows 10

import subprocess
with open('ip-source.txt') as file:
    IP = file.read()
    IP = IP.splitlines()

    for ip in IP:
        with open('output.txt','ab') as out:
            out.write(subprocess.Popen("ping " + ip))
  ===================== RESTART: F:/PingandTracert/Ping.py =====================
    Traceback (most recent call last):
      File "F:/PingandTracert/Ping.py", line 12, in <module>
        out.write(subprocess.Popen("ping " + ip))
    TypeError: a bytes-like object is required, not 'Popen'
Rachel McGuigan
  • 511
  • 4
  • 22
  • 1
    I think you are running into an issue where you need to store the subprocess in a variable first, then write it. You are missing a .communicate and two more steps see: https://stackoverflow.com/questions/16862111/python-console-and-text-output-from-ping-including-n-r as an example. – Rachel McGuigan Mar 12 '20 at 18:05
  • 1
    Take a look to this stackoverflow question/responses: https://stackoverflow.com/questions/44989808/subprocess-typeerror-a-bytes-like-object-is-required-not-str – lbcommer Mar 12 '20 at 18:13
  • Does this answer your question? [subprocess "TypeError: a bytes-like object is required, not 'str'"](https://stackoverflow.com/questions/44989808/subprocess-typeerror-a-bytes-like-object-is-required-not-str) – AMC Mar 12 '20 at 18:30

1 Answers1

0

The below is what you could use to run a ping test, I am using the subprocess module. You can write the result to a csv file or a text file, depends on how you would like to have it.

import subprocess


def pingTest(host):
    process = subprocess.Popen(["ping", "-n", "1",host], stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    streamdata = process.communicate()[0]
    if not 'Reply from {}'.format(host) in str(streamdata):
        return "Ping Failed"
    else:
        return "Ping Successful"
print(pingTest("ip"))
Shibu Tewar
  • 136
  • 1
  • 5