Matt Matt - 6 months ago 19
Python Question

How do I write a command from Command Prompt to a file using Python?

Essentially, I want to create a script with multiple choices to check certain data on a hostname. For example, the code here will have an option to ping or run a

tracert
on a given hostname.

import os

print("""What did you want to run? (pick a number)
(1) Ping
(2) Traceroute""")

runit = raw_input("> ")

print ("Enter a hostname to check")
host = raw_input("> ") #accept input for hostname

if runit == "1":
os.system("cmd /c ping " + host)
elif runit == "2":
os.system("cmd /c tracert " + host)


The code above works and I can get the results and manually copy them, but I would like this to be done automatically. I know I can open files using something like

p = open("ping1.txt", "w")


But I am not sure how to copy the results of the trace or the ping from the command prompt? Any help would be appreciated.

Answer

You can use subprocess.Popen to see the output and write to a file:

from subprocess import Popen, PIPE
print("""What did you want to run? (pick a number)
        (1) Ping
        (2) Traceroute""")

runit = raw_input("> ")

print ("Enter a hostname to check")
host = raw_input("> ") #accept input for hostname

if runit == "1":
    p  = Popen("cmd /c ping " + host, shell=True, stdout=PIPE)
    with open("ping.txt","w") as f:
        for line in iter(p.stdout.readline,""):
            print(line)
            f.write(line)

elif runit == "2":
     p = Popen("cmd /c tracert " + host, shell=True, stdout=PIPE)
     with open("trace.txt", "w") as f:
         for line in iter(p.stdout.readline, ""):
             print(line)
             f.write(line)