python 远程批量多线程paramiko 和 threading案例
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 远程批量多线程paramiko 和 threading案例相关的知识,希望对你有一定的参考价值。
初步理解多线程的好处
这两个例子告诉我们同样的事情,一个用了8s一个用了5s这就是多线程并发执行的好处。
paramiko 和 threading 多线程远程执行的基本案例
--[[email protected] 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的配置文件
目录结构
--[[email protected] 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/"
代码
--[[email protected] 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案例的主要内容,如果未能解决你的问题,请参考以下文章
用Python多进程和paramiko给主机组批量分发命令和传送文件