【发布时间】:2021-10-19 18:22:06
【问题描述】:
我制作了一个脚本,该脚本基本上扫描指定子网中的每个 IP 以查找网络服务器中的特定网络漏洞,它工作得很好,但我遇到了一个问题,即程序消耗的内存介于 6GB 之间请求具有大量 IP 的子网,例如:127.0.0.0/8 的范围在 127.0.0.0 到 127.255.255.255 之间(我认为是 1600 万个 IP), 我在程序启动时将所有 IP 存储在一个阵列上,我认为这可能是问题所在,因为该阵列将有 1600 万个 IP...如何优化它以消耗更少的内存?
这是我当前的代码:
import gc
import requests
import ipaddress
import sys
import time
from bounded_pool_executor import BoundedProcessPoolExecutor
import urllib3
urllib3.disable_warnings()
ip_list = []
vulnerable_ip_list = []
header = { 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36'}
if len(sys.argv) < 3:
print("Missing argument...")
exit()
def initialize_ip_list():
for ip in ipaddress.IPv4Network((sys.argv[1])):
ip_list.append(str(ip))
def initialize_threads():
futures = []
with BoundedProcessPoolExecutor(max_workers=int(sys.argv[2])) as executor:
for ip in ip_list:
executor.submit(scan_ip, ip)
def scan_ip(ip):
host = "http://" + str(ip) + "/vulnerableurl/"
print("Trying to fetch: " + host)
try:
r = requests.get(host, headers=header, verify=False, timeout=5)
body = r.text
if 'vulnerable page' in body.lower():
print('Vulnerability found on: ' + host)
with open("output.txt", "a") as txt_file:
txt_file.write(host + "\n")
except:
pass
print("Initializing IPs at " + str(sys.argv[1]))
initialize_ip_list()
print("Initializing work with " + str(sys.argv[2]) + " threads")
initialize_threads()
【问题讨论】:
-
直接遍历网络,而不是填充列表。此外,您主要是 I/O。考虑使用线程而不是进程。
-
谢谢大家,正如@KlausD 所说,我可以通过直接在网络上迭代来优化它。 !
标签: python arrays multithreading memory