Shell script automatically detects network disconnection and automatic reconnection


After the successful transplantation of PPP, sometimes the PPP will drop off the line. This article describes a solution to automatically detect the connection network.

Create a shell script and add something to it. (remember to give operation permission)

//Choose according to your shell type.
while true
//Let's start with a dead loop
ping -c 3 -I ppp0 >/dev/null
//Specify an exit to Ping the LAN IP of the server and redirect the result to / dev / null.
//-C 3 refers to the end of Ping after three times.
//-W3 refers to the end of Ping after 3 seconds.
if [  $? -eq 0  ];then
//There should be spaces on both sides of the []
//When Ping is successful, it returns a value of 0, and nothing needs to be done. It shows that the network is smooth.
//$? Is used to get the function return value or the exit status of the previous command.
echo "ppp0 is ready"
sleep 30
//In order to prevent excessive use of CPU resources, choose to delay for a period of time.
//If it doesn't work, it means there's something wrong with the network or the outlet.
echo "ppp0 is connecting"
pppd call connectvpn
//Redial and refresh the exit.
sleep 30
sleep 30

Delay is added to the program to reduce the CPU resources occupied by detection. This script detects network conditions once a minute.

When executing the shell, syntax error: unexpected “then” (expecting “done”) is due to the wrong encoding format. It should be fine to type it again.

PS: a script used by Linux to detect whether the program is down and automatically rerun

Write a script to replace the running of the application program, that is to start the program through the startup script, and monitor whether the program hangs up, and if so, run it again

while true
ps -ef | grep "$PWD/app/" | grep -v "grep"
if [ "$?" -eq 1 ]
/home/root/app/auto_  #Start the application and modify it to your own startup application script or command
echo "process has been restarted!"
echo "process already started!"
sleep 10


The above is the shell script introduced to you by Xiaobian, which can automatically detect network disconnection and automatic reconnection. I hope it will be helpful to you. If you have any questions, please leave me a message, and Xiaobian will reply you in time. Thank you very much for your support to the developeppaer website!
If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!