一个实现vpn简单操作的脚本

Submitted by Dot on Tue, 08/16/2016 - 10:16

本文是用curl命令提交表单的续篇,在脚本中添加了nmcli的调用,以实现连接、修改、断开等简单操作。

提示:

  • 脚本包含了注册功能,但需要目标页面没有验证或者有验证但可以绕开;
  • 脚本依赖于NetworkManager中的nmcli命令,请检查此命令是否存在于你的系统中;

 

脚本功能:

  • 若不带任何选项或参数,连接vpn;
  • 选项-c同样用于连接vpn;
  • 选项-d用于断开连接;
  • 选项-s用于显示vpn连接信息;
  • 选项-g用于修改vpn网关;
  • 选项-u用于修改vpn用户名;
  • 选项-h用于显示帮助信息;
  • 选项-v用于显示版本信息;
  • 参数为字符串时,参数1作为用户名,参数2作为密码,若只有参数1,则密码设为1111;

 

待解决的问题:

  • 脚本暂只能处理一个选项,比如,无法用-g <gateway> -c来实现修改网关并连接;
  • 同样,暂无法通过usersname passwd -c实现注册并连接;

 

完整代码如下(vpn注册地址已替换,请自行选择):


#!/bin/bash
#
# dotv

# Show version
function version(){
	echo "dotv 1.0 by Dot([email protected]) Aug 10, 2016"
	echo "More details on http://dotcra.com"
}

# Display help
function readme(){
	echo "\
Usage:
  dotv [username] [password]
  dotv [options]

Options:
  -c			connet vpn
  -d			disconnet vpn
  -s			show vpn interface info
  -g 		edit vpn gateway
  -u 		edit vpn username
  -h			display this help
  -v			display version information

Visit http://dotcra.com for more details."
}

function unknown_para(){
	echo dotv: invalid option: $1
	echo
	readme
	exit 1
}

# Get vpn connection name by awk and RE
cid=$(nmcli connection show | awk '/vpn/{print $1}')

function nmcli_conn(){
	# connect vpn
	nmcli c up $cid
}

function nmcli_dis(){
	# disconnect vpn
	nmcli connection down $cid
}

function nmcli_show(){
	# show vpn connection interface info
	nmcli connection show $cid
}

function nmcli_chgw(){
	# change vpn gateway
	nmcli c modify $cid +vpn.data "gateway = $1"
}

function nmcli_chuser(){
	# change vpn username
	nmcli c modify $cid +vpn.data "user = $1"
}

# function to register username
function reg(){
	# Check the username validity
 	if [[ $1 =~ ^[[:alnum:]_]*$ ]]; then
		echo "Registering username $1"

		# If no password given, set to 1111
		if [ -z "$2" ]; then
			passwd=1111
			echo "No password given, default 1111"
		else 
			echo "Passwd set to $2"
			passwd=$2
		fi

		# POST request by curl
		curl --data "username=$1&password1=$passwd&password2=$passwd&srvid=1&acceptterms=1&adduser=%200K%20" "http://xxx.xxx.xxx/reg.php"
		echo "Register Complete!  Try to change the vpn user."

		nmcli_chuser $1

	else
		echo "Invalid character"
		exit 2
 	fi
}

function fnmcli(){
	case $1 in
		"-c" | "")
		nmcli_conn
		;;
		"-d")
		nmcli_dis
		;;
		"-s")
		nmcli_show
		;;
		"-g")
		nmcli_chgw $2
		;;
		"-u")
		nmcli_chuser $2
		;;
		"-h")
		readme
		;;
		"-v")
		version
		;;
		-?*)
		unknown_para $1
		;;
		*)
		reg $1 $2
		;;
	esac

}

fnmcli $1 $2

Tags

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.