0

Bash program:

user@root:~/Downloads# ./program
What is the password?

So it asks for an input, and if you get the right password it continues on with the program, else it will exit (for the sake of the question, the password is a number 0 to 1000).

I need to write a Python 2 script to brute force the password. I figure the pseudocode would be something like:

import subprocess    
x = 0
while x <= 1000:
    subprocess.Popen('./program', stdin=PIPE)
    input x
    if program exits:
        continue
    else:
        break
    x += 1

I have very basic knowledge of using Popen to run a command in the terminal, however I'm not sure how to input a string using subprocess - any Googling I've done just leads me to people doing other stuff with other inputs.

I'm also stuck on how to check if the program has exited or not.

thank you :)

adam
  • 351
  • 1
  • 8
  • 17
  • Your python script needs to write on the STDIN of `./program`. This might help: https://stackoverflow.com/questions/37560427/sending-to-the-stdin-of-a-program-in-python3. Or do further research on the same concept. I did not flag is as a duplicate, as it may not totally answer your requirement. – Nic3500 Apr 16 '18 at 12:29

2 Answers2

1

Using Popen's communicate would work here:

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
Alex Stiff
  • 844
  • 5
  • 12
  • Worked perfectly. I had to add `shell=True` to the `Popen` because it was throwing some weird errors about. Thanks! :) – adam Apr 16 '18 at 13:14
0

You can try something like that:

from subprocess import check_output
import shlex

output = check_output(shlex.split(your_command_as_string))

In case your program does not accept password as command line argument, you can use following method:

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
Seer.The
  • 475
  • 5
  • 15