0

So python has a convenient function as part of pwntools where one can sendline() to an executable. How can I emulate this functionality in bash?

Example

#whatever.py
x = input("First input please: ")
y = input("Second input please: ")

I know I can echo "input1" | python3 whatever.py to answer the first input, but I can't make it work multiline (echo "input1\ninput2" | ... doesn't work, and neither does echo "input1"; echo "input2" | ...).

belkarx
  • 325
  • 1
  • 9
  • 3
    In the bash shell, you'd need `echo -e` to interpret the `\n` as a newline. Or better use `printf '%s\n' input1 input2` - see [Why is printf better than echo?](https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo) – steeldriver Apr 30 '22 at 16:52
  • This is pretty hard to answer in the abstract, since I suspect these are not the actual commands you're needing to use, but does `( echo "input1" ; echo "input2" ) | ...` or `{ echo "input1" ; echo "input2" } | ...` (with the parentheses/braces) work for your use case? – frabjous Apr 30 '22 at 17:58
  • @frabjous: with `{ }` you need `;` or newline after second (echo) command; with `( )` you don't – dave_thompson_085 May 01 '22 at 02:25
  • @frabjous Parentheses work, thank you. – belkarx May 01 '22 at 02:36

1 Answers1

1

Your Python script requires two lines of input on its standard input stream. Any of the following would provide that:

  1. Two calls to echo in a subshell:

    ( echo 'line 1'; echo 'line 1' ) | python3 whatever.py
    
  2. Two calls to echo in a compound command:

    { echo 'line 1'; echo 'line 1'; } | python3 whatever.py
    
  3. A single call to echo using the non-standard -e option to interpret the embedded \n as a literal newline:

    echo -e 'line 1\nline 2' | python3 whatever.py
    
  4. One call to printf, formatting each subsequent argument as its own line of output. This would be more suitable for variable data than using echo, see Why is printf better than echo?.

    printf '%s\n' 'line 1' 'line 2' | python3 whatever.py
    
  5. Using a here-document redirection:

    python3 whatever.py <<'END_INPUT'
    line 1
    line 2
    END_INPUT
    
Kusalananda
  • 320,670
  • 36
  • 633
  • 936