Python多线程运维脚本


需求,有一个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 

《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版]

《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码]

Python脚本获取Linux系统信息

在Ubuntu下用Python搭建桌面算法交易研究环境

Python 语言的发展简史

Python 的详细介绍:请点这里
Python 的下载地址:请点这里

本文永久更新链接地址:

相关内容