-1

I have this simple python code;

import os
os.system('cmd /k "ping google.com"')

After running the code, a cmd window is displayed with the following result;

Pinging google.com [216.58.223.238] with 32 bytes of data:
Reply from 216.58.223.238: bytes=32 time=57ms TTL=120
Reply from 216.58.223.238: bytes=32 time=26ms TTL=120
Reply from 216.58.223.238: bytes=32 time=14ms TTL=120
Reply from 216.58.223.238: bytes=32 time=9ms TTL=120

Ping statistics for 216.58.223.238:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 9ms, Maximum = 57ms, Average = 26ms

How do I copy this code from the cmd window and save to a textfile using python?

4

1 Answer 1

1

I think the simplest solution would be forwarding the output into a file.
ping -n 20 {ip_addr} >output.txt
(do ">>" to append and not overwrite)
In addition, you should use subprocess.Popen() instead of os.system() for good practice. Then you can just open the text file as usual and perform the actions you want to make.\

Edit
If you are on the command line and execute ls > output.txt, the text you normally see in your terminal will be written to the file after the ">" operator. Doing subprocess.Popen("ping -n 20 {} >> output.txt".format(ip),shell=True) is essentially the same. (I used >> in this case, to not overwrite the file with the newest output every time, but to append the new content)

import subprocess 
with open ('ip-source.txt') as file:
      test = file.read()
      test = test.splitlines()
      for ip in test:
          subprocess.Popen('ping -n 20 {} >> ping_output.txt'.format(ip),shell=True)


I hope this is the solution you were looking for and I understood you right.
Regards, Lars

Sign up to request clarification or add additional context in comments.

3 Comments

Not so understand. Can you give some example? Thank a lots!!
you have helped me solve the problem, thank a lots!!!
If so, I would appreciate if you marked the question as accepted so others know too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.