广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python 简单的多线程执行命令
  • 384
分享到

Python 简单的多线程执行命令

多线程命令简单 2023-01-31 05:01:58 384人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

Tools.py#!/usr/bin/python #coding:utf-8 import threading import subprocess import os import sys sshport = 13131 log_path

Tools.py

#!/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


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

--结束END--

本文标题: Python 简单的多线程执行命令

本文链接: https://www.lsjlt.com/news/188590.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作