在python错误中执行bash命令

时间:2015-11-18 15:59:38

标签: python bash cygwin subprocess

我正在尝试编写一个python脚本,以便在连接到本地主机时使用暴力强制(和密码)测试4位密码。需要运行的命令是:

echo password pincode | nc localhost 30002 >> /tmp/joesPin/pinNumber

(将响应写入新文件)。

这是作为bash脚本编写的,但是我正在使用Python中的子进程模块。

import subprocess

password = "UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ"

for i in range(10000):

    pincode = str('{0:04}'.format(i)) #changes 4 to 0004
    subprocess.call('echo', password, pincode,'|','nc localhost 30002 >> /tmp/joesPin/' + pincode,shell=True)

我希望它致电:

echo UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ 0001 | nc localhost 30002 >> /tmp/joesPin/0001

1 个答案:

答案 0 :(得分:0)

有多种方法可以在Python中管道输出命令。

选项1:您可以设置stdout命令的subprocess.call参数并将输出写入某处。

选项2:您可以在subprocess.PIPE调用中使用Popen并保存输出以用于其他命令。

proc = subprocess.Popen(['echo', password, pincode], stdout=subprocess.PIPE)
output = proc.communicate()[0] # now contains the output of running "proc"

file = '/tmp/joesPin/pinNumber'
with open(file, 'a+') as out:
    subprocess.call(['nc localhost 30002'], stdout=out, shell=True)

stdout中设置subprocess.call字段会将子流程的输出写入stdout中给出的文件描述符。

使用第一个进程的输出作为第二个进程的stdin输入:

proc = subprocess.Popen(['echo', password, pincode], stdout=subprocess.PIPE)
output = proc.communicate()[0] # now contains the output of running "proc"

file = '/tmp/joesPin/pinNumber'
proc2 = subprocess.Popen(['nc localhost 30002'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
proc2.stdin.write(output)
result = proc2.communicate()[0]

# now you can write the output to the file:
with open (file, 'a+') as outfile:
    outfile.write(result)