【问题标题】:how to execute python or bash script through ssh connection and get the return code如何通过ssh连接执行python或bash脚本并获取返回码
【发布时间】:2014-01-08 01:17:02
【问题描述】:

我在 \tmp\ 位置有一个 python 文件,此文件打印一些内容并返回退出代码 22。我可以使用 putty 完美运行此脚本,但无法使用 paramiko 模块执行此操作。

这是我的执行代码

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()

这是我要在远程机器上执行的 python 脚本

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

我无法理解我的逻辑实际上有什么问题。此外,当我执行 cd \tmp 然后执行 ls 时,我仍将位于根文件夹中。

【问题讨论】:

    标签: linux bash python-2.7 ssh paramiko


    【解决方案1】:

    每次运行 exec_command 时,都会启动一个新的 bash 子进程。

    这就是为什么当你运行类似的东西时:

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

    目录“hello”是在 dir 中创建的,而不是在 tmp 中。

    尝试在同一个 exec_command 调用中运行多个命令。

    另一种方法是使用python的os.chdir()

    【讨论】:

    • 好的,我知道 excec_command 不会帮助我完成我想做的事情,但是为什么我的 python/批处理脚本没有运行?另外,如果我能够做到这一点,我将如何获得脚本的退出代码或返回代码
    【解决方案2】:

    以下示例通过 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
    

    希望对你有帮助

    【讨论】:

    • 感谢您的想法。我已经通过使用管道并将 python 脚本的输出重定向到一个文件,然后在下一个命令上读取脚本来完成此操作。
    猜你喜欢
    • 1970-01-01
    • 2015-06-13
    • 2020-04-02
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 2011-01-23
    • 2011-05-09
    相关资源
    最近更新 更多