This project sets up a script that monitors VPN connection status, displays it in the tmux
status bar, and updates dynamically using systemd
timers. The goal is to provide a lightweight, efficient solution for monitoring VPN connections in real-time using tmux
.
- tmux installed and configured
- systemd available on your system (most Linux distributions include this by default)
- Basic shell scripting knowledge
-
Create the Bash script that checks the VPN status. We'll monitor the
tun0
interface (adjust as needed).Save the following script as
vpn_status.sh
under/home/$USER/
:#!/bin/bash # Path to store VPN status output STATUS_FILE="$HOME/vpn_status_output.txt" # Function to update VPN status in tmux update_tmux_for_vpn_connected() { local vpn_ip=$1 echo "$vpn_ip" > "$STATUS_FILE" # Write IP to the status file tmux refresh-client -S # Refresh tmux to show updated status } # Function to update tmux for VPN disconnected update_tmux_for_vpn_disconnected() { echo "Disconnected" > "$STATUS_FILE" # Write "Disconnected" to the status file tmux refresh-client -S # Refresh tmux } # Check VPN status and get IP address ip=$(/usr/sbin/ifconfig tun0 2>/dev/null | grep 'inet ' | awk '{print $2}') if [ -n "$ip" ]; then update_tmux_for_vpn_connected "$ip" else update_tmux_for_vpn_disconnected fi
-
Make the script executable:
chmod +x /home/$USER/vpn_status.sh
-
Edit your tmux configuration file (
~/.tmux.conf
) and add the following line to display the VPN status:set -g status-right "VPN: #(cat /home/$USER/vpn_status_output.txt) | #(whoami)@#(hostname -s)"
-
Reload tmux:
tmux source ~/.tmux.conf
-
Create a new
systemd
service file at/etc/systemd/system/vpn-status.service
:[Unit] Description=VPN Status Monitor Service [Service] ExecStart=/bin/bash /home/%i/vpn_status.sh WorkingDirectory=/home/%i User=%i StandardOutput=journal StandardError=journal [Install] WantedBy=multi-user.target
-
Create a timer file at
/etc/systemd/system/vpn-status.timer
to run the service every 5 seconds:[Unit] Description=Run VPN Status Monitor every 5 seconds [Timer] OnBootSec=5 OnUnitActiveSec=5 Unit=vpn-status.service [Install] WantedBy=timers.target
-
Reload the
systemd
daemon to recognize the new service and timer:sudo systemctl daemon-reload
-
Enable and start the timer:
sudo systemctl enable vpn-status.timer sudo systemctl start vpn-status.timer
-
Check the status of the timer and service:
systemctl status vpn-status.timer systemctl status vpn-status.service
- Open tmux and confirm that the VPN status is displayed on the right side of the tmux status bar. The status should update every 5 seconds.
To check logs or troubleshoot any issues:
journalctl -xe