Fernando Barreiro
Fernando Barreiro

Reputation: 33

Automatizing user and password filling in bash by using 'expect' for command 'systemctl restart openvpn'

I need to connect my Ubuntu 18.04 laptop to a 2 step secured VPN. To get it working, I have to write in the terminal 3 times the command 'sudo systemctl restart openvpn':

To automatize the process, I have to repeat each time I connect my laptop to Internet, I wrote the following script:

#!/usr/bin/expect -f
# shows usage to user
if {$argc!=2} {
   send_user "In order to use this script, you must provide ans user and password:\n"
   send_user "\tsudo $argv0 user password\n"
   exit 1
}
# checks for root privileges
set whoami [exec id -u]
if {$whoami!=0} {
   send_user "You must run this script with root privileges:\n"
   send_user "\tsudo $argv0 user password\n"
   exit 1
}

### Variables
## terminal wait time
#set timeout 1
#match_max 100000

# var to store the user
set user [lindex $argv 0]
# var to store the password
set password [lindex $argv 1]

### start system shell
spawn $env(SHELL)

### First command run: starts the VPN process of asking for the user and password
send -- "systemctl restart openvpn\r"
#expect "\r"

### Second command run: waits for username request
send -- "systemctl restart openvpn\r"
#expect "*?name:*"
expect -exact "Enter Auth Username: "
send "$user\r"

### Third command run: waits for password request
send -- "systemctl restart openvpn\r"
#expect  "*?assword:*"
expect -exact "Enter Auth Password: "
send "$password\r"

expect eof

But it is not working as expected, expect is not providing the correct response to the systemctl restart openvpn requests. E.g.:

But when I run 3 times the script, it fills properly the requests and I get connected.

Any advice would be useful.

Thanks in advance.

Upvotes: 1

Views: 859

Answers (1)

Fernando Barreiro
Fernando Barreiro

Reputation: 33

By using the expect's tool autoexpect I have found that to fill-in the request field "Enter Auth Password: ", the script have to send the password letter by letter, i.e. (simplifying my initial script to focus on the matter):

#!/usr/bin/expect -f
set timeout -1
spawn $env(SHELL)
match_max 100000

# First command run: start of process
send -- "systemctl restart openvpn\r"
# time between first and second systemctl to synchronize terminal responses
send -- "sleep 5\r"

# Second command run: input username (case username = username)
send -- "systemctl restart openvpn\r"
expect -exact "Enter Auth Username: "
send -- "username"
expect -exact ""
send -- "\r"

# Third command run: input password (case password = flower)
send -- "systemctl restart openvpn\r"
expect -exact "Enter Auth Password: "
send -- "f"
expect -exact "*"
send -- "l"
expect -exact "*"
send -- "o"
expect -exact "*"
send -- "w"
expect -exact "*"
send -- "e"
expect -exact "*"
send -- "r"
expect -exact "*"
send -- "\r"
send -- "exit\r"
expect eof

Now, the script works.

Upvotes: 1

Related Questions