等到paramiko exec_command完成

问题描述:

我有一个python脚本我试图安装一个rpm包,但是当我发送命令来安装它时,并不等待命令在重新启动服务之前完成。我读过很多有关使用“recv_exit_status()”的论坛,但我认为我没有正确使用它。等到paramiko exec_command完成

这是我有:

#!/usr/bin/python 

import paramiko, os 
from getpass import getpass 

# Setting Variables 
Hosts = [ '192.168.1.1', '192.168.1.2'] #IPs changed for posting 
username = 'root' 
print 'Enter root password on remote computer:' 
password = getpass() 
port = 22 
File = 'Nessus-6.11.2-es7.x86_64.rpm' 

for host in Hosts: 
    print 'Finished copying files. Now executing on remote computer' 

    #Setting up SSH session to run commands 
    remote_client = paramiko.SSHClient() 
    remote_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
    remote_client.connect(host, username=username, password=password) 

    InstallNessus = 'rpm -U --percent %s'%File 
    stdin, stdout, stderr = remote_client.exec_command(InstallNessus) 
    stdout.channel.recv_exit_status() 
    lines = stdout.readlines() 
    for line in lines: 
     print line 
    stdin, stdout, stderr = remote_client.exec_command('systemctl restart nessusd.service') 

    remote_client.close() 
+0

我试过使用Fabric但我似乎搞乱了我的语法某处。 –

channel.recv_exit_status(),不stdout.channel.recv_exit_status()

但是,由于您试图在许多服务器上运行相同的命令,类似于parallel-ssh的东西比顺序地并行地更适合并且比paramiko快得多。

代码做到这一点也更加简单,只需:

from pssh.pssh2_client import ParallelSSHClient 

hosts = ['192.168.1.1', '192.168.1.2'] 
_file = 'Nessus-6.11.2-es7.x86_64.rpm' 
cmd = 'rpm -U --percent %s' % _file 

client = ParallelSSHClient(hosts, user='<user>', password='<password>') 

output = client.run_command(cmd) 
for host, host_output in output.items(): 
    for line in host_output.stdout: 
     print "Host %s: %s" % (host, line) 
    print "Host %s exit code %s" % (host, host_output.exit_code) 

restart_out = client.run_command('systemctl restart nessusd.service') 
# Just wait for completion 
client.join(restart_out) 

进一步的信息,请参阅documentation

+0

使用你发布的内容,但它似乎也在做同样的事情。该脚本似乎没有等待rpm安装完成。我只得到“主机192.168.1.1退出码0”的输出。 虽然我会继续浏览文档。 –

+0

先测试你的命令。如果没有输出,命令可能没有执行或退出,例如,如果RPM已经安装。 – danny

+0

我是一个小菜鸟。我只是意识到我没有把完整的路径放在我的文件变量中。我认为这是我所有脚本中的问题。 –