Skip to content

Instantly share code, notes, and snippets.

@andreassiegel
Last active April 26, 2022 08:15
Show Gist options
  • Save andreassiegel/72f9521d7d6a1e58b4754e38531d136e to your computer and use it in GitHub Desktop.
Save andreassiegel/72f9521d7d6a1e58b4754e38531d136e to your computer and use it in GitHub Desktop.
Utility for VPN connections on Mac OS via Cisco AnyConnect CLI
#!/bin/bash
#
# Provides some basic utilities for VPN connections using the Cisco AnyConnect CLI.
readonly cmd="${1}"
readonly vpn="${2}"
readonly anyconnect="/opt/cisco/anyconnect/bin/vpn"
readonly configfile="${HOME}/.vpn/config"
err() {
echo "$*" >&2
}
validateCmd() {
if [[ -z "${cmd}" ]]; then
err "Command is missing"
exit 1
fi
}
validateVpnName() {
if [[ -z "${vpn}" ]]; then
err "VPN name must be provided as second argument"
exit 1
fi
local readonly vpnconfig="$(awk '/^VPN '"${vpn}"'/' ${configfile})"
if [[ -z "${vpnconfig}" ]]; then
err "Unable to find VPN ${vpn} in ${configfile}"
exit 1
fi
}
connect() {
local readonly isconnected="$(${anyconnect} state | awk '/state: Connected$/' | wc -l)"
if [ "${isconnected}" -gt 0 ]; then
err "Already connected to a VPN"
exit 1
fi
local readonly groupId="$(awk '/^VPN '"${vpn}"'$/{x=1}x&&/GroupId/{print $2;exit}' ${configfile})"
if [[ -z "${groupId}" ]]; then
err "Unable to find GroupId for VPN ${vpn} in ${configfile}"
exit 1
fi
local readonly username="$(awk '/^VPN '"${vpn}"'$/{x=1}x&&/User/{print $2;exit}' ${configfile})"
if [[ -z "${username}" ]]; then
err "Unable to find User for VPN ${vpn} in ${configfile}"
exit 1
fi
local readonly host="$(awk '/^VPN '"${vpn}"'$/{x=1}x&&/Host/{print $2;exit}' ${configfile})"
if [[ -z "${host}" ]]; then
err "Unable to find Host for VPN ${vpn} in ${configfile}"
exit 1
fi
local readonly password="$(security find-generic-password -s "${vpn}" -w)"
if [[ -z "${password}" ]]; then
err "Unable to find VPN password in keychain"
exit 1
fi
echo "Connecting user ${username} to VPN ${vpn} at ${host}..."
printf '%s\n%s\n%s\ny' "${groupId}" "${username}" "${password}" | ${anyconnect} -s connect "${host}" > /dev/null
${anyconnect} stats | awk '/(Profile Name|Client Address|Time Connected)/'
}
info() {
${anyconnect} stats
}
main() {
validateCmd
case "${cmd}" in
connect)
validateVpnName
connect "${vpn}"
;;
info)
info
;;
*)
${anyconnect} ${cmd}
;;
esac
}
set -e
main "${@}"
set +e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment