4

I want to run a python script say test.py on a Linux target machine (which has a python interpreter) and capture the output of the command in a text file as the part of another python script invoke.py using paramiko module.

The statement in the script

stdin, stdout, sterr = ssh.exec_command("python invoke.py > log.txt")

generates a blank file log.txt.

Please suggest corrections / alternate way to do this. to write the output to the file correctly.

test.py when run locally outputs sane text (which is expected to be logged in log.txt).

There are some relevant posts here and here, but no one deals with output of python script

Community
  • 1
  • 1
Bleamer
  • 637
  • 9
  • 24

1 Answers1

0

instead of calling client.exec_command() you can use client.open_channel() and use channel session's recv() and recv_stderr() streams to read write stdout/std err:

def sshExecute(hostname, username, password, command, logpath = None):

    buffSize = 2048
    port = 22

    client = paramiko.Transport((hostname, port))
    client.connect(username=username, password=password)

    if logpath == None:
        logpath = "./"

    timestamp = int(time.time())
    hostname_prefix = "host-%s-%s"%(hostname.replace(".","-"),timestamp)         
    stdout_data_filename = os.path.join(logpath,"%s.out"%(hostname_prefix))
    stderr_data_filename = os.path.join(logpath,"%s.err"%(hostname_prefix))    
    stdout_data = open(stdout_data_filename,"w") 
    stderr_data = open(stderr_data_filename,"w") 

    sshSession = client.open_channel(kind='session')
    sshSession.exec_command(command)
    while True:
        if sshSession.recv_ready():
            stdout_data.write(sshSession.recv(buffSize))
        if sshSession.recv_stderr_ready():
            stderr_data.write(sshSession.recv_stderr(buffSize))
        if sshSession.exit_status_ready():
            break

    stdout_data.close()
    stderr_data.close()
    sshSession.close()
    client.close()

    return sshSession.recv_exit_status()

Hope this fully working function helps you