Python脚本来强制bash输入

Python脚本来强制bash输入,python,bash,python-2.7,terminal,subprocess,Python,Bash,Python 2.7,Terminal,Subprocess,Bash程序: user@root:~/Downloads# ./program What is the password? 因此,它要求输入,如果你得到正确的密码,它将继续与程序,否则它将退出的问题,密码是一个数字0到1000 我需要编写一个Python2脚本来强制输入密码。我想伪代码应该是这样的: import subprocess x = 0 while x <= 1000: subprocess.Popen('./program', stdin=PIPE)

Bash程序:

user@root:~/Downloads# ./program
What is the password?
因此,它要求输入,如果你得到正确的密码,它将继续与程序,否则它将退出的问题,密码是一个数字0到1000

我需要编写一个Python2脚本来强制输入密码。我想伪代码应该是这样的:

import subprocess    
x = 0
while x <= 1000:
    subprocess.Popen('./program', stdin=PIPE)
    input x
    if program exits:
        continue
    else:
        break
    x += 1
我对使用Popen在终端中运行命令有着非常基本的了解,但是我不知道如何使用subprocess输入字符串——我所做的任何谷歌搜索都会导致人们使用其他输入做其他事情

我还被困在如何检查程序是否已退出的问题上


谢谢你:

你可以试试这样的东西:

from subprocess import check_output
import shlex

output = check_output(shlex.split(your_command_as_string))
如果程序不接受密码作为命令行参数,可以使用以下方法:

import subprocess
import shlex

prog = subprocess.Popen(
    shlex.split(your_command_as_string),
    stdin=subprocess.PIPE
) # run program with piped stdin

for password in your_passwords:
    prog.stdin.write("{}\n".format(password)) # feed password
    if prog.Poll() is not None: # check if program finished
        print(password)
        break
使用Popen的“通讯”在这里可以起作用:

import subprocess
for x in range(0,1000):
    proc = subprocess.Popen('./program', stdin=subprocess.PIPE)
    proc.communicate(str(x))
    if proc.returncode:
        continue

    print "Found the password: " + str(x)
    break

python脚本需要在./program的STDIN上编写。这可能会有所帮助:。或者对同一概念做进一步的研究。我没有把它作为一个复制品,因为它可能不完全符合你的要求。工作得很完美。我不得不将shell=True添加到Popen中,因为它抛出了一些奇怪的错误。谢谢