通过读取文本文件的内容来执行命令

Execute a command by reading contents of a text file

我想使用 python 自动执行 Linux 命令。 命令为:

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

我有一个单词列表,其中每一行都包含可能的用户名。如何编写通过读取文件来执行命令的代码?例如,我有一个名为 "users.txt" 的列表,其中包含:

robert
admin
administrator
guest

它应该按照以下步骤尝试,直到找到正确的用户和密码:

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

谢谢。

这应该有效:

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])

编辑:将其设为您的文件路径,更改为 .format(),检查结果 == 0(适用于尝试密码的 ssh)

编辑:忘记添加 shell=True