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给主机组批量分发命令和传送文件

python 通过paramiko模块批量执行ssh命令

使用paramiko批量更改root密码

paramiko模块实现批量执行远程主机命令

Python基础 - 第九天 - paramiko模块进程线程

网卡速率变化导致paramiko模块timeout的失效,多线程超时控制解决办法。