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

2021-07-09 17:08

阅读:676

标签:var   机器   odi   cat   main   17.   创建   ges   ast   

初步理解多线程的好处
技术分享图片
技术分享图片

技术分享图片
技术分享图片
这两个例子告诉我们同样的事情,一个用了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案例

标签:var   机器   odi   cat   main   17.   创建   ges   ast   

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


评论


亲,登录后才可以留言!