简体   繁体   中英

Reading lines of a file into a subprocess in Python

So I'm trying to read a list of IP addresses from a .txt into a subprocess (Nmap) in Python. It's also worth asking if the problem could be the use of quotes or not. Here's the code:

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 error message:

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 a list; you should catenate this list with 1 element list containing strline when building command line arguments:

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

The error occurs because instead of

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

you are executing something like

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

and subprocess expects to be given a list of strings, not nested lists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM