James Harzs
James Harzs

Reputation: 1913

Using expect to log into VPN from a bash script

I connect to a VPN from console using something like:

sudo openvpn my.conf
[sudo] password for user:
Enter Auth Username:my_user
Enter Auth Password:

I don't care about entering the admin pwd manually but I want to automate the vpn auth, I think expect is what I need to do this but I don't know how to use it and I never coded a bash script.

Could someone show me a simple bash script using expect so I can use it for this?

Upvotes: 1

Views: 4530

Answers (4)

KSA
KSA

Reputation: 1

#!/usr/bin/expect -f  

# creditability  
set user "username"  
set pass "password"  

spawn  openvpn  file.ovpn

expect "*?sername:*"  
send -- "$user\r"

expect "*?assword:*"  
send -- "$pass\r"

interact
close

Upvotes: 0

Bruno Nunes
Bruno Nunes

Reputation: 1

This script will work with OTP authentication too, but you need to install oathtool.

#!/usr/bin/expect

set USERNAME your_username
set PASSWORD your_password
set KEY YOUR_OTP_KEY

set OVPN_PATH /path_to_your_config_file
set OTP [exec oathtool --totp -b $KEY]

eval spawn openvpn --config $OVPN_PATH

set prompt ":|#|\\\$"
interact -o -nobuffer -re $prompt return
send "$USERNAME\r"
interact -o -nobuffer -re $prompt return
send "$PASSWORD\r"
interact -o -nobuffer -re $prompt return
send "$OTP\r"
interact

Upvotes: 0

Antonio Ocampo
Antonio Ocampo

Reputation: 61

Or maybe like this:

#!/usr/bin/expect -f  

# Constants  
set user "my_user"  
set pass "blablabla"  
set sudo_pass "blablabla"  
set timeout -1  

# Options  
match_max 100000  
log_user 0  

# Access to device  
spawn sudo openvpn my.conf
expect "[sudo]*"  
send -- "$sudo_pass\r"  

expect "*?sername:*"  
send -- "$user\r"

expect "*?assword:*"  
send -- "$pass\r"

interact
close

Upvotes: 0

pizza
pizza

Reputation: 7630

Something like that (untested)

#!/bin/usr/expect -f
spawn sudo openvpn my.conf
expect -r "\[sudo\] .*\: " {
    send "my_ownpassword\n"
}
expect "Enter Auth Username:" {
    send "my_user\n"
}
expect "Enter Auth Password:" {
    send "my_vpnpassword\n"
}
interact

Upvotes: 5

Related Questions