我有一个python脚本我正在尝试安装rpm包,但是当我发送命令进行安装时,它不会等待命令完成,然后重新启动服务。我已经阅读了很多关于使用“recv_exit_status()”的论坛,但我认为我没有正确使用它。
这就是我所拥有的:
#!/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 :(得分: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。
答案 1 :(得分:0)
add get_pty = True这将等到命令执行完成。 stdin,stdout,stderr = self.ssh.exec_command(command,get_pty = True)