0
votes

I am trying to use the below code to run a command and extract the data from the cmd.

the file with the commands and data is a txt file. (let me know if I should change it or use an excel if better).

the commands look something like this: ping "host name" which would result in some data in the cmd.there is list of these in the file. so it would ping "hostname1" then line two ping "hostname2"..etc

THE QUESTION: I want it to run every line individually and extract the results from the cmd and store them in a txt file or excel file - Ideally I want all the results in the same file. is this possible? and how?

here is the code so far:

root_dir = pathlib.Path(r"path to file here")
cmds_file = root_dir.joinpath('actual file here with commands and data') 
#fail = []
cmds = cmds_file.read_text().splitlines()

try:

for cmd in cmds:
    args = cmd.split() 
    print(f"\nRunning: {args[0]}")
    output = subprocess.check_output(args)


    print(output.decode("utf-8"))
    out_file = root_dir.joinpath(f"Name of file where I want results printed in")
    out_file.write_text(output.decode("utf-8"))
except:
pass
1
Why don't you juste use a redirection after your command ? YourCommand > YourFile.txt - Achille G
Not quite sure how to go about that but will look into it. - JuniorData

1 Answers

0
votes

You can use a module called subprocess import subprocess

Then you can define a variable like this run = subprocess.run(command_to_execute, capture_output=True)

After that you can do print(run.stdout) to print the command output. If you want to write it to a file you can do this after you run the above code

    with open("PATH TO YOUR FILE", "w") as file:
        file.write(run.stdout)

This should write a file which contains the output of your command After that close the file using file.close() and reopen it but in "a" mode

    with open("PATH TO YOUR FILE", "a") as file:
        file.write(\n + run.stdout)

This should append data to your file. Remember to close the file just for best practice, I have some bad memorys about not closing the file after I opened it :D