歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python多線程運維腳本

Python多線程運維腳本

日期:2017/3/1 9:34:14   编辑:Linux編程

需求,有一個IP列表文件 ip.txt,裡面有1000個ip,那麼我要用Python同時來處理這1000個IP。

先看ip.txt

192.168.1.1
192.168.1.2
192.168.1.3
......
192.168.1.1000

多線程並發腳本

#!/usr/bin/python
import threading
import sys
import os
import time

def ssh_cmd(ip): //定義一個ssh_cmd函數 用於發呆5秒,輸出ip
time.sleep(5)
print ip

def ssh_cmd_spit(list): //定義一個ssh_cmd_spit函數,用於執行分割後的ip列表
for j in list:
j = j.strip("\n")
ssh_cmd(j)

def thread_main(count): //定義一個thread_main函數,用於設置每個進程處理的IP個數,設置為1,那麼1000個IP需要同時開1000個線程,設置為50,那麼需要20個線程來同時處理。
file = open("ip.txt")
f = file.readlines()
for i in range(0,len(f),int(count)):
b = f[i:i+count]
t = threading.Thread(target=ssh_cmd_spit,args=(b,)) //添加線程
t.start() //處理線程

if __name__ == '__main__':
thread_main(1)

--------------------------------------分割線 --------------------------------------

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved