Xonshiz
Xonshiz

Reputation: 1367

How to give input to a batch file using Python script?

Let's say I have a batch file, which asks me for my name as input. I put my name enter. This is the manual way.

But I wanted to try something with Python. Is it possible that I make a variable in Python script and put my name in the variable and pass that variable to the bat file when it asks for input?

The very first step of my bat file is to ask me my name. Asking name batch file is for test purpose. My main batch file has this code:

@ECHO OFF

:choice
set /P c=Do you want to continue [Y/N]?
if /I "%c%" EQU "Y" goto :yes
if /I "%c%" EQU "N" goto :no
goto :choice


:yes
"scripts\enter.py" yes
goto :continue

:no
"scripts\kick_out.py" no

:continue
pause 
exit

So, I hope this helps. I want to pass about 2 inputs. First Y and other when it calls enter.py it asks my login details. My username and password. So, I need to make 3 inputs. How can I do that?

Upvotes: 4

Views: 8894

Answers (1)

lucasg
lucasg

Reputation: 11002

It is feasible : I use it to inject attack string which use non-printable ascii characters (like null bytes).

Example using Python 3 :

inject_string.py

import ctypes
import time
import subprocess
import binascii


if __name__ =="__main__":
    response = "Y"

    p = subprocess.Popen("echo.bat", stdin = subprocess.PIPE)
    time.sleep(2)

    p.stdin.write(bytes(response, 'ascii')) #Answer the question
    print("injected string :", response)

echo.bat

@ECHO OFF

:choice
set /P c=Do you want to continue [Y/N]?
if /I "%c%" EQU "Y" goto :yes
if /I "%c%" EQU "N" goto :no
goto :choice

:yes
echo "User has typed yes"
goto :continue

:no
echo "User has typed no"

:continue
pause

Output

python inject_string.py
Do you want to continue [Y/N]?injected string : Y
"User has typed yes"

Upvotes: 1

Related Questions