在Python中将文件行读入子流程

时间:2015-02-13 21:40:55

标签: python python-2.7 subprocess nmap

所以我试图将.txt中的IP地址列表读入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])

Trusty错误消息:

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'

1 个答案:

答案 0 :(得分:2)

shlex.split返回一个列表;在构建命令行参数时,您应该使用包含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给出一个字符串列表,而不是嵌套列表。