1. 程式人生 > >python 遠程批量多線程paramiko 和 threading案例

python 遠程批量多線程paramiko 和 threading案例

man 技術分享 main 分享 str ces 就是 圖片 target

初步理解多線程的好處
技術分享圖片
技術分享圖片

技術分享圖片
技術分享圖片
這兩個例子告訴我們同樣的事情,一個用了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案例