0

I'm writing a python script capturing FQDN from within the remote host's itself just for some sanity checks, below is the small code I'm trying to run and want to capture the stdoutout of the same into my current host from i'm running it but rather its creating files into the remote hosts, and not the one from where I'm running.

#!/usr/bin/python3 system_name = socket.gethostname() f = open("output.txt", "a") print("Hostname: {}".format(system_name, file=f) f.close() 

OR

#!/usr/bin/python3 system_name = socket.gethostname() sys.stdout=open("output.txt","a") print("Hostname: {}".format(system_name) sys.stdout.close() 

Even i tried adopting like but that didn't worked though.

name = 'mycurrenthost' system_name = socket.gethostname() short_sysname = socket.gethostname().split('.', 1)[0] if short_sysname == name: f = open("output.txt", "a") print("Hostname: {}".format(system_name), file=f) f.close() 

My example myhostlist looks like..

mydbhost1 mydbhost2 mydnhost3 mydbhost4 

Below id how I'm executing the above code..

$ for host in `cat myhostlist`;do timeout -t 20 ssh -o "StrictHostKeyChecking no" "$host" "python -s" < ./myPythonScript.py;done 

My output on the current console while not writing to a file...

Hostname: mydbhost1.example.com Hostname: mydbhost2.example.com: Hostname: mydnhost3.example.com: Hostname: mydbhost4.example.com: 

please help

1 Answer 1

1

You're running the python application on the remote host; what do you expect it to do? It runs on the remote host, it writes to files on the remote host - it can't write to files locally -it does not have access to the file system from where you initiate the ssh session.

Instead you can print out the result to stdout with just print, and then capture the standard output locally in the shell with >> output.txt after the command (>> means that the output will be appended to output.txt).

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

2 Comments

Okay, you mean there is no way to collect the print which is being displayed on the current shell to the file? yes, redirecting the output to the shell is always a option.
Not within the python program itself, no. That runs on the remote server, and can't write content to your local storage area (which would be a security nightmare). The python process is invoked on the remote server, and that's where the code runs. Redirect the output to a local file through the shell redirection support (and make sure you don't run the redirect on the remote server).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.