標籤:var 機器 odi cat main 17. 建立 ges ast
初步理解多線程的好處
這兩個例子告訴我們同樣的事情,一個用了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案例