简体   繁体   English

如何通过ssh连接执行python或bash脚本并获取返回码

[英]how to execute python or bash script through ssh connection and get the return code

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. 我在位置\\ tmp \\这个文件打印了一个python文件并返回退出代码22.我能用putty完美地运行这个脚本但是无法用paramiko模块执行它。

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 这是我在远程机器上执行的python脚本

#!/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. 另外当我做cd \\ tmp然后ls时,我仍然会在根文件夹中。

The following example runs a command via ssh and then get command stdout, stderr and return code: 以下示例通过ssh运行命令,然后获取命令stdout,stderr和返回代码:

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 希望能帮助到你

Each time you run exec_command, a new bash subprocess is being initiated. 每次运行exec_command时,都会启动一个新的bash子进程。

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. dir“hello”是在dir中创建的,而不是在tmp中创建的。

Try to run several commands in the same exec_command call. 尝试在同一个exec_command调用中运行多个命令。

A different way is to use python's os.chdir() 另一种方法是使用python的os.chdir()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM