Question

I have a python file at the location \tmp\ this file print something and return with exit code 22. I'm able to run this script perfectly with putty but not able to do it with paramiko module.

this is my execution code

import paramiko    
def main():
    remote_ip = '172.xxx.xxx.xxx'
    remote_username = 'root'
    remote_password = 'xxxxxxx'
    remote_path = '/tmp/ab.py'
    sub_type = 'py' 
    commands = ['echo $?']
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_client.connect(remote_ip, username=remote_username,password=remote_password)
    i,o,e = ssh_client.exec_command('/usr/bin/python /tmp/ab.py') 
    print o.read(), e.read()
    i,o,e = ssh_client.exec_command('echo $?')
    print o.read(), e.read()


main()

this is my python script to be executed on remote machine

#!/usr/bin/python
import sys
print "hello world"
sys.exit(20)

I'm not able to understand what is actually wrong in my logic. Also when i do cd \tmp and then ls, i'll still be in root folder.

Was it helpful?

Solution

The following example runs a command via ssh and then get command stdout, stderr and return code:

import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname='hostname', username='username', password='password')

channel = client.get_transport().open_session()
command = "import sys; sys.stdout.write('stdout message'); sys.stderr.write(\'stderr message\'); sys.exit(22)"
channel.exec_command('/usr/bin/python -c "%s"' % command)
channel.shutdown_write()

stdout = channel.makefile().read()
stderr = channel.makefile_stderr().read()
exit_code = channel.recv_exit_status()

channel.close()
client.close()

print 'stdout:', stdout
print 'stderr:', stderr
print 'exit_code:', exit_code

hope it helps

OTHER TIPS

Each time you run exec_command, a new bash subprocess is being initiated.

That's why when you run something like:

exec_command("cd /tmp");
exec_command("mkdir hello");

The dir "hello" is created in dir, and not inside tmp.

Try to run several commands in the same exec_command call.

A different way is to use python's os.chdir()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top