多进程实现多台服务器ssh命令:
代码语言:javascript复制# -*- coding: UTF-8 -*-
from multiprocessing import Process,Pool
import paramiko
import sys,os
host_list = (
('192.168.1.60','nginx','password'),
('192.168.1.62','nginx','password'),
('192.168.1.66','nginx','password'),
)
cmd='free -m'
pkey_file='/root/.ssh/id_rsa'
paramiko.util.log_to_file('syslogin.log')
ssh=paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
key = paramiko.RSAKey.from_private_key_file(pkey_file)
def ssh_run(host_info,cmd):
ip,username,password = host_info
ssh.connect(hostname=ip,port=22,username=username,password=password,pkey=key,timeout=5)
stdin,stdout,stderr=ssh.exec_command(cmd)
cmd_result = stdout.read(),stderr.read()
print "-----------------%s---------------------------------" %ip,username
for line in cmd_result:
print line,
p = Pool(processes=2)
result_list = []
for h in host_list:
result_list.append(p.apply_async(ssh_run,[h,'df']))
p.close()
p.join()
for res in result_list:
print res.get()