Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I open a file in python and insert one or more inputs to it?

I've been trying to code a bit of a "game" to help others learn python, but I've run into a wall right after I jumped out of the brainstorming phase. See, it involves making a script open another script, and then insert input to it. For example:

username = raw_input('Insert username:')
password = raw_input('Insert password:')
if username == user:
  if password == 1234:
    print('Congratulations, you cracked it!')

This would be my source code. Then I'd have another code, in which I'd write something to open the former script, insert "user" as if I'd typed it myself in the command prompt, and then tried to insert every number between 0 and, say, 10000. So something like:

for n in range(0, 10000)
  [Insert script to open file]
  [input 'user']
  [input n]

How would I go on about to code the last part?

like image 987
Robly18 Avatar asked Feb 14 '23 16:02

Robly18


2 Answers

The subprocess module lets you run another program—including a script—and control its input and output. For example:

import subprocess, sys
p = subprocess.Popen([sys.executable, 'thescript.py'], stdin=subprocess.PIPE)
p.stdin.write('user\n')
p.stdin.write('{}\n'.format(n))
p.wait()

If you can build all the input at once and pass it as a single string, you can use communicate.

If you also want to capture its output, add another PIPE for stdout.

import subprocess
p = subprocess.Popen(['python', 'thescript.py'], 
                     stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = p.communicate('user\n{}\n'.format(n))

For details on how this works, read the documentation; it's all explained pretty well. (However, it's not organized perfectly; you might want to read the opening section, then skip down to "Replacing Older Functions", then read the "Frequently Used Arguments", then come back to the top and go through in order.)

If you need to interact with it in any way more complicated than "send all my input, then get all the output", that gets very hard to do correctly, so you should take a look at the third-party pexpect module.

like image 152
abarnert Avatar answered May 10 '23 01:05

abarnert


Would this be what you wanted?

import subprocess

for n in range(0, 10000):
        p = subprocess.Popen("python another_script.py", shell=True,
                    stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        p.stdin.write("user\n" + str(n) + "\n")
        out = p.stdout.read()
        if "cracked" in out:
                print "cracked: " + str(n)
                break
like image 42
Specur Avatar answered May 10 '23 01:05

Specur