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

Python2.7使用subprocess.Popen报错:'Popen'对象不可迭代

解决subprocess.Popen返回对象不可迭代的问题

Got it, let's break this down for you. The TypeError you're hitting happens because subprocess.Popen() returns a process object, not the actual text output from nmap. That object can't be iterated over or checked with in directly. To fix this, you need to first capture nmap's output, then check for your target port in that text.

正确实现的步骤

  1. Capture nmap's output: When initializing Popen, add stdout=subprocess.PIPE to capture the command's standard output (add stderr=subprocess.PIPE too if you need error logs).
  2. Read the output content: Use the process object's communicate() method to fetch the output. This returns a tuple (stdout_data, stderr_data)—we care about the stdout part here.
  3. Check for the port: Convert the output to a string (in Python 2.7, stdout is a byte stream that works directly for string checks) and verify if your target port's identifier exists in it.

示例代码

import subprocess

def is_port_open(target_ip, port):
    # Build nmap command to scan a single port with concise output
    nmap_command = ["nmap", "-p", str(port), target_ip]
    # Start the process and capture output
    scan_process = subprocess.Popen(
        nmap_command,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    # Read output and error streams
    stdout, stderr = scan_process.communicate()

    # Check if the port string and "open" status exist in the output
    # Adjust this match based on nmap's default output format
    port_identifier = f"{port}/tcp"
    if port_identifier in stdout and "open" in stdout:
        return True
    return False

# Test the function
target_host = "127.0.0.1"
target_port = 22
if is_port_open(target_host, target_port):
    print(f"Port {target_port} is open on {target_host}")
else:
    print(f"Port {target_port} is closed/filtered on {target_host}")

额外优化建议

  • For more reliable parsing, have nmap output XML (add -oX - to the command) and use Python's xml.etree.ElementTree to parse results. This avoids edge cases with text matching.
  • In Python 2.7, if you run into encoding issues with the output, convert it to Unicode using stdout.decode('utf-8') before checking.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:32:21