前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 简单的多线程执行命令

Python 简单的多线程执行命令

作者头像
py3study
发布2020-01-08 11:33:55
1.7K0
发布2020-01-08 11:33:55
举报
文章被收录于专栏:python3

Tools.py

代码语言:javascript
复制
#!/usr/bin/python
#coding:utf-8
import threading
import subprocess
import os
import sys
sshport = 13131
log_path = 'update_log'
output = {}
def execute(s, ip, cmd, log_path_today):
    with s:      
        cmd = '''ssh -p%s root@%s -n "%s" ''' % (sshport, ip, cmd)
        ret = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        output[ip] = ret.stdout.readlines()
if __name__ == "__main__":
    if len(sys.argv) != 3:
        print "Usage: %s config.ini cmd" % sys.argv[0]
        sys.exit(1)
                                     
    if not os.path.isfile(sys.argv[1]):
        print "Usage: %s is not file!" % sys.argv[1]
        sys.exit(1)
                                         
    cmd = sys.argv[2]
                                     
    f = open(sys.argv[1],'r')
    list = f.readlines()
    f.close()
    today = datetime.date.today()
    log_path_today = '%s/%s' % (log_path,today)
    if not os.path.isdir(log_path_today):
        os.makedirs(log_path_today)
                                     
    threading_num = 100
    if threading_num > len(list):
        threading_num = len(list)
    s = threading.Semaphore(threading_num)
                                     
    for line in list:
        ip = line.strip()
        t = threading.Thread(target=execute,args=(s, ip,cmd,log_path_today))
        t.setDaemon(True)
        t.start()
                                         
    main_thread = threading.currentThread()
    for t in threading.enumerate():
        if t is main_thread:
            continue
        t.join()
                                         
    for ip,result in output.items():
        print "%s: " % ip
        for line in result:
            print "    %s" % line.strip()
                                     
    print "Done!"

脚本读取两个参数,第一个为存放IP的文本,第二个为shell命令

效果如下:

144632398.png
144632398.png

够简单的哈。。。直接调用ssh。。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档