Shell script automatically detects network disconnection and automatic reconnection

Time:2020-10-1

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)

#!/bin/sh
//Choose according to your shell type.
while true
//Let's start with a dead loop
do
ping -c 3 -I ppp0 172.16.1.11 >/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.
else
//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.
ifconfig
sleep 30
fi
sleep 30
done

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

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

summary

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!