首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >paramiko多线程

paramiko多线程
EN

Stack Overflow用户
提问于 2018-01-25 02:07:44
回答 1查看 8.3K关注 0票数 3

上下文

如果有一个连接到服务器的脚本,然后滚动本地主机以获取我需要的信息。

问题

我的问题是,我需要从大约200台服务器上获取信息,我使用的方法,大约需要15分钟才能完成,这还不错,但我想做的事情更先进,如果我能锁定多线程,我可以完成更多。

期望结果

我只想有一个5-10的线程池,这样我就可以更快地获取我需要的信息。

代码语言:javascript
复制
from Queue import Queue
from multiprocessing.pool import ThreadPool
import threading, os, sys
import socket
from threading import Thread
#socket.setdefaulttimeout(5)
from time import sleep
import paramiko
hosts = []
hostnames = []
def capture_travelinfo(host):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    print('Connecting to ' + host)
    ssh.connect(host, username='root', key_filename='...')
    print('Connected to ' + host)
    stdin, stdout, stderr = ssh.exec_command('curl localhost:4000')
    stdin.close()
    ssh.close()

def main():
    try:
        file = open('IPs.txt')
        threads = []
        content = file
        for x in content:
            fields = x.strip().split()
            UNIT = [fields[0], fields[1]]
            hosts.append(UNIT)
        for x in hosts:
            host = x[1]
            hostnames.append(x[1])
            ip = x[0]
            pool = ThreadPool(5)
            results = pool.map(capture_travelinfo, hostnames)
            pool.close()
            pool.join()
            print(results)

以前的尝试

我环顾了一下,发现了一些相关的东西,但所有有用的材料都不包括线程池,因此我最终一次连接到大约200个主机,这是不好的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-25 03:02:20

代码语言:javascript
复制
from multiprocessing.pool import ThreadPool
import paramiko
hosts = []
hostnames = []


def capture_travelinfo(host):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    print('Connecting to ' + host)
    ssh.connect(host, username='root', key_filename='...')
    print('Connected to ' + host)
    stdin, stdout, stderr = ssh.exec_command('curl localhost:4000')
    stdin.close()
    ssh.close()


def main():
    ips = open('IPs.txt')
    pool = ThreadPool(5)
    for ip in ips:
        fields = ip.strip().split()
        UNIT = [fields[0], fields[1]]
        hosts.append(UNIT)
    for ip in hosts:
        hostnames.append(ip[1])
    results = pool.map(capture_travelinfo, hostnames)
    pool.close()
    pool.join()
    print(results)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48434552

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档