【问题标题】:Python - How to make multiple GET requests at oncePython - 如何一次发出多个 GET 请求
【发布时间】:2021-08-10 15:03:38
【问题描述】:

我目前正在为本地网络开发网站扫描仪,我需要一次运行多个请求,我已经尝试使用线程,但它给了我异常并且程序崩溃了,如果我有它可以正常工作只有几个网址,这是我目前的代码:

import requests
import ipaddress
import sys
import time
import threading
import urllib3
urllib3.disable_warnings()

ip_list = []
vulnerable_ip_list = []

if len(sys.argv) < 3:
    print("Missing argument...")
    exit()

def initialize_ip_list():
    for ip in ipaddress.IPv4Network(unicode(sys.argv[1])):
        ip_list.append(str(ip))
    
    print("IP List initialized, please wait for the program to finish.")
    
def initialize_threads():
    if len(ip_list) < int(sys.argv[2]):
        print("More threads than ips, limiting threads to " + str(len(ip_list)))
        for i in range(len(ip_list)):
            t1=threading.Thread(target=scan_ip)
            t1.start()
    else:
        for i in range(int(sys.argv[2])):
            t1=threading.Thread(target=scan_ip)
            t1.start()

def scan_ip():
    ip = ip_list.pop(0)
    try:
        host = "http://" + str(ip) + "/testurl/"
        r = requests.get(host, verify=False, timeout=5)
        status_code = r.status_code
        body = r.text
    
        if 'vulnerable test' in body.lower():
            print('Found Vulnerable URL: ' + host)
            with open("output.txt", "a") as txt_file:
                txt_file.write(ip + "\n")
    except:
        pass
    
    time.sleep(0.1)
    if len(ip_list) > 0:
        scan_ip()

initialize_ip_list()
initialize_threads()

这也是我遇到的错误:

Exception in thread Thread-27:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "scanner.py", line 50, in scan_ip
    scan_ip()

感谢任何愿意帮助我的人。

【问题讨论】:

  • 试试 ThreadPoolExecutor
  • 你需要一个线程安全的数据结构来存储 IP 地址,否则东西会变得一团糟。试试Queue。信号处理确保在某个时间只有一个线程可以访问它的数据。
  • 除了@nagyl 评论,您还可以在initialize_threadsip_list.pop(0) 并将ip 作为参数传递给函数。不一定需要排队。
  • 我将尝试使用@Elazar 提到的 ThreadPoolExecutor,我会在稍后返回结果
  • ThreadPoolExecutor 似乎暂时解决了这些问题,谢谢大家的帮助!

标签: python multithreading python-requests request


【解决方案1】:

对于遇到此问题的任何人:

  • 我首先使用答案中提到的@Elazar 的 ThreadPoolExecutor 解决了这个问题,但是当我处理数百万个数据时它给了我内存泄漏

我做了什么来解决这个问题:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 2019-09-07
    • 2021-06-04
    • 2021-08-04
    • 1970-01-01
    • 2016-11-08
    相关资源
    最近更新 更多