Image

Knowledge base → Setting up a crontab script to avoid high load

[Virtual servers]
Date of publication: 27.01.2023

When none of the protection services were able to repel the attack or the server began to work under high load for another reason. We suggest installing the script and running it every minute through the crontab service. This will allow you not to lose access to the server during critical loads and take measures to eliminate this situation.

/etc/cron.daily/load-average-2.sh

#!/bin/bash

loadavg=`uptime | awk '{print $10+0}'`
# bash doesn't understand floating point
# so convert the number to an interger
thisloadavg=`echo $loadavg|awk -F \. '{print $1}'`
if [ "$thisloadavg" -ge "2" ]; then
echo "Busy - Load Average $loadavg ($thisloadavg) "
echo 'Warning - Load AVG (my.server.tld) on:' `date` `uptime` | mailx -s "Warning: LA from `uptime | cut -d'(' -f2 | cut -d')' -f1`" -S smtp=smtp://mail.server.tld -S smtp-auth=login -S smtp-auth user=user@domain.tld -S smtp-auth-password=PassW0rd -S from="LLC COMPANY" to@domain.tld

else
echo "Okay - Load Average $loadavg ($thisloadavg) "
fi

This script must be saved in the file load-average-2.sh in the /etc/cron.daily folder and set execution rights.

Then you need to add a line via the crontab -e command to run it every 2 minutes:

*/2 * * * * /etc/cron.daily/load-average-2.sh >> /dev/null 2>&1

The values must be replaced with your own:

  • my.server.tld - the name of the server on which you are installing the script.
  • mail.server.tld - the domain name of the mail server through which the script will send you notifications.
  • user@domain.tld - mailbox name for connecting to the mail server (login).
  • PassW0rd - password for your mail account.
  • LLC COMPANY - name and address from whom the letter will be sent.
  • to@domain.tld - mailing address where the notification will be sent.

If the load average exceeds 2 i.e. 200% (2 cores), the script will send a notification. This parameter is highlighted, you can change it to your own depending on the number of cores the server has. For example, if you have 4 cores, then the maximum load will be 4, i.e. 400%.

If necessary, you can add commands to the script that need to be executed, for example, restarting services to shed the load. You need to add them before else, for example:

service nginx restart
service ddos restart
service httpd restart




No Comments Yet