You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python多主机批量请求问题:遍历主机时复用查询参数

问题原因

问题出在文件对象的遍历特性上:当你第一次遍历strings文件对象时,文件指针会移动到文件末尾,后续再尝试遍历它就没有内容可读了,所以脚本只处理完第一个主机就终止。

修复方案

有两种简单的修复方式:

方式1:提前读取所有查询参数到列表

把strings1.txt里的所有内容先读取到一个列表中,这样每个主机循环都能重新遍历这个列表:

import requests  # 原脚本遗漏了requests库的导入,必须补上

with open('hosts.txt','r') as file:
    # 先把所有查询参数读到列表里,同时过滤空行
    with open('strings1.txt','r') as strings:
        params = [s.strip() for s in strings if s.strip()]
    
    for line in file:
        host = line.strip()
        if not host:  # 跳过主机列表里的空行
            continue
        for string in params:
            url = f"https://{host}/?test={string}"
            resp = requests.get(url).status_code
            print(f'Results for {url}\n{resp}')  # 原脚本里的test是笔误,改成resp

方式2:每次处理主机前重置文件指针

在每个主机循环开始时,把strings文件的指针移回文件开头,这样每次都能重新遍历所有参数:

import requests

with open('hosts.txt','r') as file:
    with open('strings1.txt','r') as strings:
        for line in file:
            host = line.strip()
            if not host:
                continue
            # 把文件指针重置到开头,重新读取所有参数
            strings.seek(0)
            for string in strings:
                string = string.strip()
                if not string:  # 跳过参数列表里的空行
                    continue
                url = f"https://{host}/?test={string}"
                resp = requests.get(url).status_code
                print(f'Results for {url}\n{resp}')
额外修正

原脚本存在一个语法错误:print语句里的{test}是未定义变量,必须改成{resp},否则运行时会抛出NameError异常。

内容的提问来源于stack exchange,提问作者NoobSec

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 15:22:12