Simplify OpenConnect with Shell + expect

Use a small expect script to automate OpenConnect VPN login steps at home, reducing repetitive prompts.

Sep 15, 2018 · 1 min read · 137 Words · -Views -Comments · Programming
Linux 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

I often need to VPN into the company from home. The repeated steps are tedious, so I wrote a small shell/expect script to streamline it.

Previous Operation

As shown, every time I had to enter the OpenConnect command, a hard‑to‑remember IP, and go through 5 interactive prompts. Time to automate it with a shell script.

Shell automation

Except for the final OTP/password (which I still enter manually), all other inputs can be scripted. I use expect to handle the interactive prompts.

Install expect

Run brew install expect.

Script

Save as vpn.sh:

#!/usr/bin/expect
# vpn to xxx
spawn sudo openconnect 1.1.1.1
expect "Password" {send "xxxxxxxx\r"}
expect "Enter 'yes' to accept" {send "yes\r"}
expect "Username:" {send "xxx\r"}
expect "Password" {send "xxx\r"}
interact

Done. To connect:

  1. ./vpn.sh
  2. Enter the one‑time code manually

Much faster.

Reference

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover