#!/usr/bin/env python
#-*- coding:utf-8 -*-
from multiprocessing import Process,Pool
import time,paramiko,sys,os
host_list = (
('16.74.185.167','root','123456','df -Th'),
('139.128.34.22','root','123456','df -Th')
)
s = paramiko.SSHClient() #绑定实例
s.load_system_host_keys() #加载本机.ssh/knows_host文件
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
def ssh_run(host_info):
ip,username,password,cmd = host_info
s.connect(ip,22,username,password,timeout=5)
stdin,stdout,stderr = s.exec_command(cmd)
cmd_result = stdout.read(),stderr.read()
print ' 33[32;1m----------------%s------------------ 33[0m' %ip
for line in cmd_result:
print line,
p = Pool(processes=1) #1表示单进程,根据cpu核数定,一般是几个核就写几
result_list = []
for h in host_list:
result_list.append(p.apply_async(ssh_run, [h,]))
for res in result_list:
res.get()
s.close()
命令已经写死
高级版:自定义命令显示结果并手动退出
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from multiprocessing import Process,Pool
import time,paramiko,sys,os
host_list = (
('10.174.85.167','root','123456'),
('139.16.139.15','root','123456'),
('139.24.11.58','root',666448..')
)
s = paramiko.SSHClient() #绑定实例
s.load_system_host_keys() #加载本机.ssh/knows_host文件
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
def ssh_run(host_info,cmd):
ip,username,password = host_info
s.connect(ip,22,username,password,timeout=5)
stdin,stdout,stderr = s.exec_command(cmd)
cmd_result = stdout.read(),stderr.read()
print ' 33[32;1m----------------%s------------------ 33[0m' %ip
for line in cmd_result:
print line,
p = Pool(processes=2)
result_list = []
q='quit'
e='exit'
#------通过输入来判断------
while True:
input_cmd = raw_input("please input command:").strip()
if input_cmd == q or input_cmd == e:
break
else:
for h in host_list:
result_list.append(p.apply_async(ssh_run, [h,input_cmd]))
for res in result_list:
res.get()
s.close()