Search code examples
pythonsubprocesswmic

Python 2.7 Loop through multiple subprocess.check_output calls


I am having an issue with printing output from subprocess.check_output calls. I have a list of IP addresses in ip.txt that I read from and save to list ips. I then iterate over that list and call wmic command to get some details from that machine, however only the last command called prints output. By looking at CLI output, I can see that print 'Complete\n' is called for each, but check_output is not returning anything to output variable.

Any ideas? Thanks

Python Code:

from subprocess import check_output

f_in = open('ip.txt', 'r')
ips = []

for ip in f_in:
    ips.append(ip)

f_in.close()
f_out = open('pcs.txt','w')

for ip in ips:
    cmd = 'wmic /node:%s computersystem get name,username' % (ip)
    f_out.write('Trying %s\n'%ip)
    print 'Trying: %s' % (ip)
    try:
        output = check_output(cmd,shell=True)
        f_out.write(output)
        print 'Output\n--------\n%s' % output
        print 'Complete\n'
    except:
        f_out.write('Could not complete wmic call... \n\n')
        print 'Failed\n'

f_out.close()

File Output:

Trying 172.16.5.133

Trying 172.16.5.135

Trying 172.16.5.98

Trying 172.16.5.131
Name        UserName        
DOMAINWS48  DOMAIN\staff

CLI Output

Trying: 172.16.5.133

Output

Complete

Trying: 172.16.5.135

Output

Complete

Trying: 172.16.5.98

Output

Complete

Trying: 172.16.5.131

Output

Name UserName DOMAINWS48 DOMAIN\staff

Complete


Solution

  • In these lines you read a file line by line:

    f_in = open('ip.txt', 'r')
    ips = []
    
    for ip in f_in:
        ips.append(ip)
    

    Unfortunately each line has an end of line character still terminating each line. You then pass the newline in as part of the IP address. You might want to consider stripping the newlines \n from the end of each line you read:

    f_in = open('ip.txt', 'r')
    ips = []
    
    for ip in f_in:
        ips.append(ip.strip('\n'))
    

    strip('\n') will strip all the newlines from the beginning and end of the string. Information on this string method can be found in the Python documentation:

    str.strip([chars])

    Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

    You can also read all the lines from the file with something like:

    ips = [line.strip('\n') for line in f_in.readlines()]
    

    My guess is that your ip.txt file has an IP address on each line and the last line of the file is not terminated with a newline \n and in that case your code worked.