shell 脚本 常规操作
#!/bin/bash #检查输入的参数 if [ $# != 3 ] ; then echo "参数输入格式不对" echo "例如: $0 A B C " echo "参数1:XX" echo "参数2:XX" echo "参数3:XX" exit fi #获取网卡名称 check_iface() { def_iface=$(route 2>/dev/null | grep -m 1 '^default' | grep -o '[^ ]*$') [ -z "$def_iface" ] && def_iface=$(ip -4 route list 0/0 2>/dev/null | grep -m 1 -Po '(?<=dev )(\S+)') def_state=$(cat "/sys/class/net/$def_iface/operstate" 2>/dev/null) if [ -n "$def_state" ] && [ "$def_state" != "down" ]; then if ! uname -m | grep -qi -e '^arm' -e '^aarch64'; then case $def_iface in wl*) exiterr "Wireless interface '$def_iface' detected. DO NOT run this script on your PC or Mac!" ;; esac fi NET_IFACE="$def_iface" else eth0_state=$(cat "/sys/class/net/eth0/operstate" 2>/dev/null) if [ -z "$eth0_state" ] || [ "$eth0_state" = "down" ]; then exiterr "Could not detect the default network interface." fi NET_IFACE=eth0 fi echo "物理网卡名称 :$NET_IFACE" } check_iface DIR=/usr/lib/node_modules if [[ ! -d $DIR ]];then mkdir /usr/lib/node_modules fi if [ -f /usr/local/src/xxx.zip ];then unzip -d /usr/lib/node_modules/ /usr/local/src/xxx.zip else echo "xxx.zip文件不存在,请先上传文件!" exit fi #修改配置 DEVDIR=/etc/devname.conf if [[ $? -eq 0 ]];then echo -e "\033[32m 正在修改devname.conf配置....\033[0m" > DEVDIR echo '{ "name":"'${3}'" }' > $DEVDIR fi #给脚本追加 IPSSECRETSDIR=/etc/ipsec.secrets if [[ $? -eq 0 ]];then echo -e "\033[32m 正在修改ipsec.conf配置....\033[0m" > IPSSECRETSDIR echo ' : PSK "'${3}'"' >> $IPSSECRETSDIR fi #判断版本号 release_num=$(lsb_release -r --short) if [[ $? -eq 0 ]];then if [ $release_num == 18.04 ];then systemctl stop strongswan systemctl start strongswan else systemctl stop strongswan-starter.service systemctl start strongswan-starter.service fi fi #开机自启动配置开始 RCLOCALSERDIR=/etc/systemd/system/rc-local.service if [[ $? -eq 0 ]];then echo -e "\033[32m 新建rc-local.service...\033[0m" if [ ! -f $RCLOCALSERDIR ];then touch $RCLOCALSERDIR fi fi if [[ $? -eq 0 ]];then echo -e "\033[32m 正在设置开机自动执行服务....\033[0m" > RCLOCALSERDIR echo '[Unit] Description=/etc/rc.local Compatibility ConditionPathExists=/etc/rc.local After=network.target [Service] Type=forking ExecStart=/etc/rc.local start TimeoutSec=0 StandardOutput=tty RemainAfterExit=yes SysVStartPriority=99 [Install] WantedBy=multi-user.target ' > $RCLOCALSERDIR fi RCLOCALCFGDIR=/etc/rc.local if [[ $? -eq 0 ]];then echo -e "\033[32m 新建rc.local..\033[0m" if [ ! -f $RCLOCALCFGDIR ];then touch $RCLOCALCFGDIR fi fi if [[ $? -eq 0 ]];then echo -e "\033[32m 正在设置开机自动执行脚本....\033[0m" > RCLOCALCFGDIR echo '#!/bin/bash iptables -t nat -A PREROUTING -p tcp -m tcp ! --dport 26881 -s 11.0.0.0/8 ! -d 11.0.0.0/8 -j REDIRECT --to-ports 7000 iptables -t nat -I POSTROUTING -o '$NET_IFACE' -j MASQUERADE exit 0' > $RCLOCALCFGDIR fi if [[ $? -eq 0 ]];then chmod 754 /etc/rc.local systemctl enable rc-local fi #开机自启动配置结束 if [[ $? -eq 0 ]];then echo -e "\033[32m 关闭防火墙...\033[0m" ufw disable fi
参考:https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/vpnsetup_ubuntu.sh