Search code examples
pythonlinuxlistmoduleexecute

Execute a command by reading contents of a text file


I want to automate a Linux command using python. The command is:

smbmap -u robert -p p@ssw0rd -H 192.168.2.10

I have a wordlist which includes possible usernames in each line. How can I write a code which execute the command by reading the file? For example I have a list called "users.txt" which contains:

robert
admin
administrator
guest

And it should try as follow till it finds the correct user&password:

smbmap -u robert -p p@ssw0rd -H 192.168.2.10
smbmap -u admin -p p@ssw0rd -H 192.168.2.10
smbmap -u administrator -p p@ssw0rd -H 192.168.2.10
smbmap -u guest -p p@ssw0rd -H 192.168.2.10

Thanks.


Solution

  • This should work:

    import subprocess
    
    # read in users and strip the newlines
    with open('/tmp/users.txt') as f:
        userlist = [line.rstrip() for line in f]
    
    # get list of commands for each user
    cmds = []
    for user in userlist:
        cmds.append('smbmap -u {} -p p@ssw0rd -H 192.168.2.10'.format(user))
    
    # results from the commands
    results=[]
    
    # execute the commands
    for cmd in cmds:
        results.append(subprocess.call(cmd, shell=True))
    
    # check for which worked
    for i,result in enumerate(results):
        if result == 0:
            print(cmds[i])
    

    Edit: made it your file path, changed to .format(), checked result == 0 (works for ssh trying passwords)

    Edit: forgot to add shell=True