Hi all,
I have been trying to use python to automate a sequence of processes on my computer, one of which is starting a hosted network. I have used subprocess to interact with command prompt (windows 10), and am struggling to pass sequential commands. I am trying to first send the administrator password, since it needs to run with administrator rights, and then netsh commands to set up and run a hosted network. Here is what i have come up with so far:

    prog = sp.Popen(['runas', '/noprofile', '/user:Administrator', 'CMD.exe'], stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
    data = prog.stdout.read()   #get cmd output
    data = data.decode('utf-8') #decode from byte to string
    prog.stdout.seek(0)         #set read position to start
    command = 'adminpasswd'     
    command = command.encode('utf-8')   #encode pwd to byte
    prog.stdin.write(command)           #write pwd to cmd

    data = prog.stdout.read()   #get cmd output
    data = data.decode('utf-8') #decode from byte to string

The first read attempt works fine, it prints the "enter administrator password" prompt. However, any subsequent commands i send and then try to read the output of return blank. Ive tried the command 'netsh wlan show drivers' since I know this will return something to read, yet my program still reads ''. Am I sending the commands correctly, or am I just reading in the wrong places?
Many thanks

6 Months
Discussion Span
Last Post by Gribouillis

It is very difficult to run an interactive session with the subprocess module. Some of your statements look suspicious, such as prog.stdout.read() instead of prog.stdout.readline() to read a single line, prog.stdout.seek(0) (prog.stdout is not a regular file). If you write lines to prog.stdin, the lines should end with a newline character, also it would probably be a good idea to call prog.stdin.flush() in order to ensure that the line is not buffered somewhere instead of being sent to the program.

Anyway, IMHO, it would be much better to find a way to call the commands in a non interactive way. You could use the /c option in CMD.exe, or perhaps call netsh command without wrapping it in a CMD command. You can perhaps write a batch file that does a part of the job and you could call this batch file with the subprocess module.

Edited by Gribouillis

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.