Requirements: Batch distribution of commands to host groups with multi-threaded python
Script content:
[[Email protected] opt]# cat index.py #!/usr/bin/env python#coding:utf-8import threadingimport paramikoimport timewhile true: time.sleep (3) comd = raw_input (' Please enter the command you want to distribute in bulk: ') 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 threads simultaneous execution num += 1 ip= ' 192.168.200.%s ' %num #三台机器的IP地址 &nBsp; 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) #最大连接数, that is, the number of concurrently running threads for i in range (3): t = threading. Thread (target=run,args= (i,)) #这里定义了三个线程, the maximum number of connections above is set to three, that is, the three threads will be running concurrently t.start ()
Execution results show:
650) this.width=650; "Src=" Http://s1.51cto.com/wyfs02/M00/86/55/wKiom1e8B5iwu0hIAAA4SHQ3evY163.png-wh_500x0-wm_3 -wmp_4-s_3796095202.png "title=" qq picture 20160823162139.png "alt=" Wkiom1e8b5iwu0hiaaa4shq3evy163.png-wh_50 "/>
This article is from the "Wsyht blog" blog, make sure to keep this source http://wsyht90.blog.51cto.com/9014030/1841575
Batch distribution of commands to host groups with Python multithreading