Created
December 12, 2017 01:26
-
-
Save ljjjustin/2bafc153b9b0f9d57355926133a3417a to your computer and use it in GitHub Desktop.
setup ssh vpn in one script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
vpn_server=10.70.239.196 | |
vpn_tunnel_id=8 | |
vpn_ip_prefix=192.168.48 | |
vpn_monitor_port=50008 | |
ensure_tun_device() { | |
local host=$1 | |
local device=$2 | |
device_info=$(ssh root@${host} -- ip -o link | grep -w "${device}") | |
if [ -z "${device_info}" ]; then | |
ssh root@${host} -- ip tuntap add ${device} mode tun | |
fi | |
} | |
ensure_iptable_rules() { | |
local host=$1 | |
iptable_rule=$(ssh root@${host} -- iptables-save -t nat | grep ${vpn_ip_prefix}) | |
if [ -z "${iptable_rule}" ]; then | |
ssh root@${host} -- iptables -t nat -A POSTROUTING -s ${vpn_ip_prefix}.0/24 -j SNAT --to-source ${host} | |
fi | |
} | |
start_sshvpn() { | |
local device=$1 | |
autossh -M ${vpn_monitor_port} \ | |
-o PermitLocalCommand=yes \ | |
-o ServerAliveInterval=60 \ | |
-w ${vpn_tunnel_id}:${vpn_tunnel_id} root@${vpn_server} \ | |
-o LocalCommand="ifconfig ${device} ${vpn_ip_prefix}.2 pointopoint ${vpn_ip_prefix}.1 netmask 255.255.255.0" \ | |
"ifconfig ${device} ${vpn_ip_prefix}.1 pointopoint ${vpn_ip_prefix}.2 netmask 255.255.255.0; echo ssh vpn ready" | |
} | |
change_route() { | |
ip r rep 10.0.0.0/8 via 10.70.238.1 | |
ip r rep default via ${vpn_ip_prefix}.1 | |
} | |
device_name="tun${vpn_tunnel_id}" | |
ensure_tun_device localhost ${device_name} | |
ensure_tun_device ${vpn_server} ${device_name} | |
ensure_iptable_rules ${vpn_server} | |
start_sshvpn ${device_name} | |
change_route |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment