2013-12-19 80 views
0

我在位置\ tmp \此文件中有一个python文件打印某些内容并返回退出代码22.我能够完美地运行此脚本腻子,但不能与paramiko模块做到这一点。如何通过ssh连接执行python或bash脚本并获取返回码

这是这是远程机器

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

上执行我的Python脚本,我无法理解什么是我的逻辑其实是错误的我执行代码

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

。另外当我做cd \ tmp然后ls时,我仍然会在根文件夹中。

回答

2

下面的例子通过SSH可以运行一个命令,然后得到的命令标准输出,标准错误并返回代码:

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 

希望它有助于

+0

感谢您的想法。我已经通过使用管道并将python脚本的输出重定向到一个文件然后在下一个命令中读取脚本来完成此任务。 – Hemant

0

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

这就是为什么当你运行像:

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

在dir “你好” 在目录中创建,而不是内部的TMP。

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

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

+0

确定我理解,excec_command不会帮助我完成我想要做的事情,但为什么我的python /批处理脚本没有运行?另外,如果我无论如何我能够这样做,我怎么会得到退出代码或返回代码的脚本 – Hemant

相关问题