Connect CISCO Anyconnect VPN via bash
Although expect
can be cleaner, it is not strictly necessary. Assuming /opt/cisco/anyconnect/bin/vpnagentd
is running as it automatically should be:
To connect:
printf "USERNAME\nPASSWORD\ny" | /opt/cisco/anyconnect/bin/vpn -s connect HOST
Replace USERNAME
, PASSWORD
, and HOST
. The \ny
at the end is to accept the login banner - this is specific to my host, and so you may not need it.
I understand that there are obvious security concerns with this method; it's for illustration purposes only.
To get state:
/opt/cisco/anyconnect/bin/vpn state
To disconnect:
/opt/cisco/anyconnect/bin/vpn disconnect
This was tested with AnyConnect v3.1.05160.
I had to download the expect packages (yum install expect). Here is the code I used to automate vpn connection
#!/usr/bin/expect
eval spawn /opt/cisco/anyconnect/bin/vpn connect vpn.domain.com
expect "Username: " { send "username\r" }
expect "Password: " { send "password\r" }
set timeout 60
expect "VPN>"
Real easy! :D
If you are using macOS, I recommend to save your vpn password in Keychain, then request it from your Anyconnect script.
For example, say I want to connect to foo.bar.com
with account foo
and password bar
.
- Save
foo
andbar
pair in Keychain (login not iCloud) with namefookey
- Run the following bash script to connect
/opt/cisco/anyconnect/bin/vpn connect foo.bar.com -s << EOM
0 # foo.bar.com doesn't require two factor authorization
foo # vpn account
$(sudo security find-generic-password -ws fookey) # vpn password
EOM
Using this approach, you don't need to type in your vpn password every time, and you won't write your password to files without encryption.
If you are not familiar with bash script, read below for explanation:
/opt/cisco/anyconnect/bin/vpn connect -s
enters non-interactivel mode.<< EOM ... EOM
is called here-docs, which uses a string to replace a file. It is very useful to script interactive CLI, by writing each respond as a new line.security
is a nice tool to access your Keychain from the command line.