Here’s a way to handle the unexpected downtime of your Virtual Private Server (VPS) automatically, especially if your provider uses a Virtualizor panel. If you often find your VPS powered off and need a manual restart, you might consider automating this process using a simple bash script.
Prerequisites
Before diving into the script, ensure you have the following:
- Your VPS IP address, API key, and password, which you can usually retrieve from your hosting provider's control panel.
Bash Script to Monitor and Restart VPS
Here's a bash script that continuously checks if your VPS is up and running. If the server is down, it will automatically stop and then restart the VPS.
#!/bin/bash
# Variables
VPS_IP="" # VPS IP address
API_KEY="" # API key provided by your hosting service
API_PASSWORD="" # API password provided by your hosting service
PANEL_URL="https://panel.example.com:4083" # URL to your Virtualizor panel
SVS="" # Service ID for your VPS
# Function to stop the VPS
stop_vps() {
curl -k -L "${PANEL_URL}/index.php?svs=${SVS}&act=stop&api=json&apikey=${API_KEY}&apipass=${API_PASSWORD}&do=1"
}
# Function to start the VPS
start_vps() {
curl -k -L "${PANEL_URL}/index.php?svs=${SVS}&act=start&api=json&apikey=${API_KEY}&apipass=${API_PASSWORD}&do=1"
}
# Main loop to ping the VPS and check its status
for i in {1..3}; do
echo "Attempt $i: Pinging ${VPS_IP}..."
if ping -c 1 -W 5 $VPS_IP &> /dev/null; then
echo "VPS is up and running."
exit 0
else
echo "Ping failed, no response after 5 seconds."
fi
if [ $i -eq 3 ]; then
echo "Max retries reached. Stopping and starting the VPS..."
stop_vps_output=$(stop_vps)
echo "Stop VPS output: $stop_vps_output"
sleep 5 # wait for the VPS to shut down
start_vps_output=$(start_vps)
echo "Start VPS output: $start_vps_output"
sleep 120 # wait for the VPS to start up
fi
sleep 5 # Wait before retrying
done
Explanation of the Code
- Variables: These should be filled with your specific VPS details.
- Functions:
stop_vps
andstart_vps
use cURL to send requests to the Virtualizor API to stop and start the VPS respectively. - Ping Check: The script attempts to ping the VPS up to three times. If all attempts fail, it proceeds to restart the VPS.
- Automation: After stopping the VPS, it waits for 5 seconds before starting it again. Then it waits another 2 minutes to allow for boot up.
This script can be set up as a cron job on another server or on a local machine that remains operational, ensuring that your VPS has minimal downtime. This method keeps your server management proactive and can significantly reduce the hassle of manual monitoring and restarting.