python 远程批量多线程paramiko 和 threading案例
2021-07-09 17:08
标签:var 机器 odi cat main 17. 创建 ges ast paramiko 和 threading 多线程远程执行的基本案例 if name == "main": ============================== host_list = [ ] 代码 if name == "main": python 远程批量多线程paramiko 和 threading案例 标签:var 机器 odi cat main 17. 创建 ges ast 原文地址:http://blog.51cto.com/13945009/2167603
这两个例子告诉我们同样的事情,一个用了8s一个用了5s这就是多线程并发执行的好处。
--[root@scsv01181 pythontest]# cat paramiko-threading.py
#!/usr/bin/python
#coding:utf-8
#from settings.py import *
import paramiko
import threading
import time
def tunction(ip,username,password,command):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ip,username= username,password=password)
stdin,stdout,stdeer = client.exec_command(command)
print stdout.read()
client.close()
def main(host_list,command):
thread_list = []
for ip,username,password in host_list:
t = threading.Thread(target = tunction,args = (ip,username,password,command))
thread_list.append(t)
for th in thread_list:
th.start()
for th in thread_list:
th.join()host_list = [
("10.133.107.8","gluster_zabbix","gluster"),
("10.133.107.9","gluster_zabbix","gluster"),
]
command = "ls /tmp/"
main(host_list,command)
优化:当我们的机器很多而且需要经常修改我们可以单独做一个配置文件
创建一个settings.py的配置文件
目录结构
--[root@scsv01181 pythontest]# cat settings.py
#!/usr/bin/python
#coding:utf-8
("10.13.17.8","glustqeqr_zabbix","gluqwester"),
("10.13.17.9","glustewrer_zabbix","glursdaster"),
command = "ls /var/"
--[root@scsv01181 pythontest]# cat paramiko-threading.py
#!/usr/bin/python
#coding:utf-8
from settings import *
import paramiko
import threading
import time
def tunction(ip,username,password,command):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ip,username= username,password=password)
stdin,stdout,stdeer = client.exec_command(command)
print stdout.read()
client.close()
def main(host_list,command):
thread_list = []
for ip,username,password in host_list:
t = threading.Thread(target = tunction,args = (ip,username,password,command))
thread_list.append(t)
for th in thread_list:
th.start()
for th in thread_list:
th.join()main(host_list,command)
下一篇:html
文章标题:python 远程批量多线程paramiko 和 threading案例
文章链接:http://soscw.com/essay/102878.html