title: Automate input to brute-force a program running in cli with Python
body: <p>I'm currently trying to complete all levels on Over the Wire's Bandit 'wargame'.</p>
  
  <p>One of the levels (level 24), requires that I connect to a port, on which a daemon is running. This daemon asks to input a password and a 4-digit pin. The password is already known (it is provided at the end of the previous level), the pin is unknown. The indication is that it's necessary to 'brute-force' it.</p>
  
  <p>Entering a wrong pin results in this message:  "Wrong! Please enter the correct pincode. Try again.".</p>
  
  <p>I decided to write a python script that automates the process. The script would: 
  1) Connect to the port via netcat
  2) Enter the password and a randomly generated pin
  3) Read the output, and, if the word 'again' is in it (meaning the pin is wrong), repeat via a loop, until the pin is guessed.</p>
  
  <p>But although my script runs and connects, it fails to communicate with the daemon, once the connection to its port is established.</p>
  
  <p>All I get is the daemon's prompt, requesting password and pin. </p>
  
  <p>This is my code:</p>
  
  <pre><code>import subprocess
  import random
  
  
  # Initialise variables
  
  pin = ''
  
  output = "Wrong! Please enter the correct pincode. Try again."
  
  
  # Connect to the port
  def connect_to_port():
      subprocess.call(["nc localhost 30002"], shell=True)
  
  
  # Generate pin
  # TO DO: skip pins that were proven incorrect
  def generate_pin():
      pin = ''
      pin_len = 0
      while pin_len &lt; 4:
          pin += str(random.randint(0, 9))   
          pin_len += 1 
      return pin   
  
  
  # Connect to port
  # Loop: check if 'again' is in 'output',
  # if it is, generate a pin and input password and pin
  def main():
      connect_to_port()
      while 'again' in output:
          pin = generate_pin()
          out = subprocess.check_output(["UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ", pin])
          output = out.decode("utf-8")
  
  main()
  </code></pre>
  
  <p>I suspect I'm not using the <code>subprocess</code> module correctly, but I can't really understand how. Why is my script not working? </p>
  
  <p>Forgive my rudimentary use of the relevant terminology.</p>
  
  <p>EDIT: I see the use of <code>subprocess.check_out()</code> is all wrong. What I'd need, as suggested in the answers and comments, is to open a PIPE and use <code>communicate()</code> to write to the subprocess's <code>stdin</code> (modifying the pin each time) and read its <code>stdout</code>, but I'm not sure how to go about that.</p>