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

來源:互聯網
上載者:User

標籤: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案例

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.