bash OpenConnect 自动连接/重新连接脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27940254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
OpenConnect autoconnect/reconnect script?
提问by Andrius
I have this script:
我有这个脚本:
#!bin/bash
NAME="user"
PIDFILE="openconnect.pid"
CERT="user.crt"
KEY="user.key"
PASS="pass"
HOST="https://example.com"
SCRIPT="/etc/vpnc/vpnc-script"
openconnect -b --script $SCRIPT --pid-file=$PIDFILE -c $CERT -k $KEY --key-password=$PASS --user=$NAME $HOST
It works, but sometimes if something goes wrong (restart of server, or some other issues), it disconnects from VPN. And I need to rerun script again. Is there some way I could modify it or add it in cron job or some other way?
它可以工作,但有时如果出现问题(服务器重启或其他一些问题),它会与 VPN 断开连接。我需要再次重新运行脚本。有什么方法可以修改它或将其添加到 cron 作业或其他方式中吗?
Note. When I run this script I need to enter certificate password. So considering security, I'm wondering where I should keep that password for autoreconnect purposes?
注意。当我运行这个脚本时,我需要输入证书密码。因此,考虑到安全性,我想知道为了自动重新连接的目的,我应该在哪里保存该密码?
回答by dawez
You can detect if openconnect is still running by checking its PID:
您可以通过检查其PID来检测 openconnect 是否仍在运行:
pidof openconnect
pidof openconnect
This return an exit value of 0 if openconnect still runs otherwise non zero.
如果 openconnect 仍然运行,则返回退出值 0,否则非零。
You would have a script that looks like that [not tested but should give you a hint]:
你会有一个看起来像这样的脚本 [未经测试但应该给你一个提示]:
#!/bin/bash
OPENCONNECT_PID=""
function checkOpenconnect(){
ps -p "${OPENCONNECT_PID}"
# print the status so we can check in the main loop
echo $?
}
function startOpenConnect(){
# start here open connect with your params and grab its pid
openconnect [your params] & OPENCONNECT_PID=$!
}
startOpenConnect
while true
do
# sleep a bit of time
sleep 30
OPENCONNECT_STATUS=$(checkOpenconnect)
[ $OPENCONNECT_STATUS -ne 0 ] && startOpenConnect
done