首页 > 编程语言 > 详细

python 远程批量多线程paramiko 和 threading案例

时间:2018-08-31 15:39:19      阅读:189      评论:0      收藏:0      [点我收藏+]
初步理解多线程的好处
技术分享图片
技术分享图片

技术分享图片
技术分享图片
这两个例子告诉我们同样的事情,一个用了8s一个用了5s这就是多线程并发执行的好处。

paramiko 和 threading 多线程远程执行的基本案例
--[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()

if name == "main":

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

host_list = [
("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()

if name == "main":

main(host_list,command)

python 远程批量多线程paramiko 和 threading案例

原文:http://blog.51cto.com/13945009/2167603

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!