Running OpenVPN on an isolated network namespace

It may be convenient to run select processes over VPN instead of applying the VPN connection system-wide. vpnshift by GitHub user crasm lets you run commands in an isolated network namespace with OpenVPN. Updates were made to crasm’s original repository in this forked version with additional funtionalities and command line options.



Download this vpnshift bash script and follow the instructions below:

  1. Apply VPN to a single process(COMMAND).

     sudo bash ./vpnshift -c <OVPN FILE> -i <INTERFACE> -u <USER> [<COMMAND> [<ARG>...]]
  2. Establish a VPN network namespace with a dummy ping command.

     sudo bash ./vpnshift -c <OVPN FILE> -i <INTERFACE> -u <USER> ping

    ..and attach multiple processes to it.

     sudo ip netns exec <NAMESPACE> sudo -u <USER> [<COMMAND> [<ARG>...]]

Example scripts

Bash script to run firefox on an existing network namespace:

usage="usage: bash -n <netns>"

quick_die() {
	format="$1"; shift
	>&2 printf "${format}\n" "$@"
	exit 1

main() {
	while getopts "hn:" opt; do
		case "${opt}" in
			h) quick_die "${usage}" ;;
			n) netns="${OPTARG}" ;;
			*) quick_die "unknown option: %s" "${opt}" ;;
	shift $(( OPTIND - 1 ))

	if [[ -z "${netns}" ]]; then
		quick_die "network namespace is required"

	sudo ip netns exec $netns sudo -u $USER firefox

main "$@"