0
votes

I am using subprocess in python to execute a custom vpn command which excepts password to execute. below is the command which asks password:

./vpn -u <user_id> -d "description" /var/tmp/1.txt
password: XXXX

below is vpn shell command which works perfectly for above command.

/usr/bin/expect -c 'spawn  ./vpn -u <user_id> -d "description" /var/tmp/1.txt; expect "Password"; send "<Password here>\r"; interact'

In python I am trying to achieve the same with below subprocess module, where below script executes below is the output.

"(b"\x1b[31m\xe2\x9c\x97 Can't read 'user id' password from the console.\x1b[0m""

import subprocess

args = ["./vpn", "-u", "<user_id>", "-d", "description", "/var/tmp/1.txt"]
# args = ['sudo','cat', '/var/tmp/1.txt']

proc = subprocess.Popen(args, 
                        stdin=subprocess.PIPE, 
                        stdout=subprocess.PIPE, 
                        stderr=subprocess.PIPE)

proc.stdin.write('<passowrd>'.encode())
stdout, stderr = proc.communicate()

print(stdout)

Note: if I use time.sleep(2) before writing password, it prompts me for password in console without any error and my goal is to give password in the script.

Is there any better way in python to pass the shell command as this is pretty lengthy OR provide password in subprocess module execute seamlessly.

2
Does the "vpn" executable have any sort of non-interactive option for the password? Like reading it from a file, or environment variable? - geonaut
No this is a custom binary and there is no other option to give password. - Vinod HC

2 Answers

0
votes

You are using Expect for Shell/Bash CLI command. When you use Python, just use pexpect to get the same functionality in Python.

Explore pexpect at https://github.com/pexpect/pexpect

Example passing password at executed program is here: https://github.com/pexpect/pexpect/blob/master/examples/passmass.py

Example:

import pexpect
child = pexpect.spawn('ftp ftp.openbsd.org')
child.expect('Name .*: ')
child.sendline('anonymous')
child.expect('Password:')
child.sendline('[email protected]')
0
votes

I tried in shell script and it works well: Just for anyone if it will be help full:

/usr/bin/expect<<vpn
spawn ./vpn -u <user_id> -d "description" /var/tmp/1.txt
expect "Password"
send "<password here>\r"
interact
sleep 5 
vpn
echo "It's done"