Skip to content
Advertisement

How to extract the output of a cmd query to a textfile using python

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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement