# !/usr/bin/env python
import paramiko
import threading
import time
def commands(hostname, ip, username, passwd, cmd):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, 22, username, passwd, timeout=5)
# ssh.connect(ip,22,username,passwd)
for m in cmd:
stdin, stdout, stderr = ssh.exec_command(m)
out = stdout.readlines()
for o in out:
print('主机%s执行结果%s' % (hostname, o)),
#return '主机%s执行结果%s' % (hostname, o)
print('%s\tOK\n' % (hostname))
ssh.close()
except Exception as e:
print('%s\tError\n %s时间:%s' % (hostname, e, time.strftime("%Y-%m-%d %H:%M:%S")))
if __name__ == '__main__':
# cmd = ['mysql -e "use suhua; create table names(id int,name char(11))"','echo $?']
cmd = ['yum -y install redis', 'echo $?']
hostname = 'c2.com'
username = "root"
passwd = "Aa123456"
threads = []
print("Begin......")
# for i in range(1,10):
# print(i)
# ip = '192.168.1.10'+str(i)
# a=threading.Thread(target=commands,args=(hostname,ip,username,passwd,cmd))
# a.start()
host_list = ['192.168.1.105', '192.168.1.106']
for ip in host_list:
print(ip)
a = threading.Thread(target=commands, args=(hostname, ip, username, passwd, cmd))
a.start()