1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
| [iyunv@test1 opt]# cat index.py
#!/usr/bin/env python
#coding:utf-8
import threading
import paramiko
import time
while True:
time.sleep(3)
comd = raw_input('请输入你要批量分发的命令:')
num = 9 #定义IP最后一位数的初始值
def run(n):
private_key_path = '/root/.ssh/id_rsa' #输入Key的路径
key = paramiko.RSAKey.from_private_key_file(private_key_path) #获得key
ssh = paramiko.SSHClient() #获取连接ssh方法
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #获允许连接不在know_hosts文件中的主机
global num #加上global可以在局部变量改全局变量的值
samp.acquire() #加上锁,4线程同时执行
num += 1
ip='192.168.200.%s' %num #三台机器的IP地址
ssh.connect(hostname=ip, port=22, username='root', pkey=key) #连接相关信息
stdin, stdout, stderr = ssh.exec_command(comd) #执行命令
print stdout.read() #输出命令
ssh.close(); #关闭
samp.release() #解锁
samp = threading.BoundedSemaphore(3) #最大连接数,也就是同时运行的线程数
for i in range(3):
t = threading.Thread(target=run,args=(i,)) #这里定义了三个线程,上面最大连接数又设为了三,也就是会同时运行这三个线程
t.start()
|