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

Python调用subprocess执行rustscan报错TypeError: 预期str而非tuple

问题原因及修复方案

核心报错原因

你代码中存在4个直接触发报错的语法/逻辑问题:

  • cmd 本身已经是由命令参数组成的元组,subprocess.Popen 要求第一个参数为一维的参数列表/元组,你将cmd额外套了一层[]变成嵌套结构,导致subprocess无法识别可执行文件路径,抛出类型错误
  • 没有接收Popen的返回值,也没有等待进程执行完成就直接读取输出,会导致无法获取到完整扫描结果
  • 打开文件时模式参数w没有加引号,属于语法错误
  • 打开的文件对象赋值给了变量f,写文件时误用了未定义的file变量

修复后的代码

单独修正PortScan函数

def PortScan():
    YN = str(input('[+] Would you like to run a port scan? ')).lower()
    portDir = Dir +'/portscan.txt'
    print(portDir)
    if YN in ('y', 'yes'):
        print('[+] Starting portscan.\n    [+] The results can be found here: ' + portDir )
        cmd = ["rustscan", "-a", ip_addr, "--", "-sV", "-sC", "-A"]
        print(cmd)
        # 直接传cmd作为参数,接收返回值并等待进程执行完成
        result = sub.Popen(cmd, stdout=sub.PIPE, stderr=sub.STDOUT, text=True)
        stdout, _ = result.communicate()
        # 修正文件打开模式的引号与变量名
        with open(portDir, "w") as f:
            f.write(stdout)
    elif YN in ('n', 'no'):
        return
    else:
        print('[-] Invalid input!\n[-] Please try again.')
        PortScan()

额外优化说明

  • 输入判断新增.lower()处理,兼容用户输入大写的Y/Yes等场景
  • 将stderr合并到stdout写入文件,避免扫描过程的错误信息丢失
  • 输入非法时递归调用PortScan重新获取输入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:12:02