2017-11-10 69 views
0

我有一個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但我似乎搞亂了我的語法某處。 –

回答

0

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

我是一個小菜鳥。我只是意識到我沒有把完整的路徑放在我的文件變量中。我認爲這是我所有腳本中的問題。 –