I had to enter a two-step code, so I had to use the following template.
connect host
username
pass
twostep
y
exit
/opt/cisco/anyconnect/bin/vpn -s < anyconnect.txt
On Mac (Ventura 13.2.1) I wanted to integrate keychain and two-step together so I made the following script. It retrieves the key used for two-step, uses python OTP library to get the two-step code, and also uses keychain to get the password. Then connects to Cisco Connect.
Note that first you need to create the keychain entries as described in the blog referred below. Maybe for testing you can initially hardcode key
and password
.
Make sure to edit [Username] and [Host]. I had them hardcoded rather than keychain on Mac.
import time
import pyotp
import subprocess
key = subprocess.check_output("security find-generic-password -w -a $LOGNAME -s key", shell=True)[:-1].decode("utf-8")
uri = pyotp.totp.TOTP(key).provisioning_uri()
totp = pyotp.TOTP(key)
key = totp.now()
print(key)
password = subprocess.check_output("security find-generic-password -w -a $LOGNAME -s key_password", shell=True)[:-1].decode("utf-8")
output = subprocess.check_output(f"/opt/cisco/anyconnect/bin/vpn -s connect [Host] <<'EOF'\n[UserName]\n{password}\n{key}\ny\nEOF", shell=True)
print(output)
Ref: https://blog.koehntopp.info/2017/01/26/command-line-access-to-the-mac-keychain.html
Steps to create keychain items :
- Add
otp_key
to keychain :
security add-generic-password -T "" -a $LOGNAME -s [hostname_otp] -w [otp_key]
- Add password of host :
security add-generic-password -T "" -a $LOGNAME -s [hostname_username] -w [host_password]
Steps to retrieve saved key and password :
- Retrieve host's
otp_key
security find-generic-password -w -a $LOGNAME -s [hostname_otp]
- Retreive password of
hostname_username
security find-generic-password -w -a $LOGNAME -s [hostname_username]
This will make sure that there is an extra step to connecting to host, i.e. retrieving secret info from keychain after providing the password, rather than hardcoding in a file.