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.
正确实现的步骤
- Capture nmap's output: When initializing
Popen, addstdout=subprocess.PIPEto capture the command's standard output (addstderr=subprocess.PIPEtoo if you need error logs). - 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. - 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'sxml.etree.ElementTreeto 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
相关产品推荐
相关产品推荐

