将文件行读入 Python 中的子进程

Reading lines of a file into a subprocess in Python

所以我正在尝试将 IP 地址列表从 .txt 读取到 Python 中的子进程 (Nmap) 中。同样值得一问的是问题是否出在引号的使用上。这是代码:

addressFile = raw_input("Input the name of the IP address list file.  File must be in current directory." )
fileObj = open(addressFile, 'r')


for line in fileObj:
    strLine = str(line)
    command = raw_input("Please enter your Nmap scan." )
    formatCom = shlex.split(command)
    subprocess.check_output([formatCom, strLine])

可信赖的错误信息:

Traceback (most recent call last):
  File "mod2hw7.py", line 15, in <module>
    subprocess.check_output([formatCom, strLine])
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 566, in check_output
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 709, in __init__
    errread, errwrite)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1326, in _execute_child
    raise child_exception
AttributeError: 'list' object has no attribute 'rfind'

shlex.split returns 一个列表;在构建命令行参数时,您应该将此列表与包含 strline 的 1 个元素列表连接起来:

formatCom = shlex.split(command)
subprocess.check_output(formatCom + [strLine])

错误发生是因为

subprocess.check_output([ 'nmap', '-sT', '8.8.8.8' ])

你正在执行类似

的操作
subprocess.check_output([ ['nmap', '-sT'], '8.8.8.8' ])

subprocess 期望得到一个字符串列表,而不是嵌套列表。