Linux - Ubuntu - LAMP Server installation.sh
#!/bin/bash
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <hostname>"
exit 1
fi
# Set the correct timezone
timedatectl set-timezone Europe/Rome
# Set the hostname
hostnamectl set-hostname $1
if [ -f /etc/cloud/cloud.cfg ]; then
sed -i 's/preserve_hostname: false/preserve_hostname: true/' /etc/cloud/cloud.cfg
fi
# Update the system and install some utilities
apt update && apt upgrade -y
apt install -y zip unzip htop iftop tasksel net-tools pwgen
# Disable some MOTD files
chmod -x /etc/update-motd.d/10-help-text
chmod -x /etc/update-motd.d/50-motd-news
chmod -x /etc/update-motd.d/80-livepatch
# Create an additional MOTD file to display the network interfaces addresses
cat <<"EOT" >> /etc/update-motd.d/55-ip-addresses
#!/bin/sh
echo
echo "-------------------- Network interfaces --------------------"
ip -4 -br addr show
echo "------------------------------------------------------------"
EOT
chmod +x /etc/update-motd.d/55-ip-addresses
# SSH - Enable password authentication
sed -i 's/^#Port/Port/' /etc/ssh/sshd_config
sed -i 's/^Port 22/Port 31322/' /etc/ssh/sshd_config
sed -i 's/^#PermitRootLogin/PermitRootLogin/' /etc/ssh/sshd_config
sed -i 's/^PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
sed -i 's/^PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config
sed -i 's/^#PasswordAuthentication/PasswordAuthentication/' /etc/ssh/sshd_config
sed -i 's/^PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config
service ssh restart
# Add some configuration files
# --------------------------------------------------
# /root/.bash_aliases
# --------------------------------------------------
cat <<"EOT" >> /root/.bash_aliases
alias l='ls -l'
alias ll='ls -lha'
alias sl='ls'
alias ..='cd ..'
alias sbrc='source ~/.bashrc'
alias phplintr='find . -type f -name "*.php" -not -path "./vendor/*" -exec php -l {} \;'
alias cpu_usage='cat /proc/loadavg | cut -c 1-4 | echo "scale=2; ($(</dev/stdin)/`nproc`)*100" | bc -l'
EOT
# --------------------------------------------------
# /root/.bashrc
# --------------------------------------------------
cat <<"EOT" >> /root/.bashrc
# --------------------------------------------------
# PS1 variable customization
# --------------------------------------------------
# The original __git_ps1 helper can be really slow.
# As we are interested in only the branch name, this approach is much faster
# We also do it only if a .git folder exists
parse_git_branch() {
[ -d ".git" ] && git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
PS1_1='\n${debian_chroot:+($debian_chroot)}\[\033[01;31m\]\u\[\033[00m\]@\[\033[01;32m\]\H\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]'
#PS1_2='$(__git_ps1 " (%s)")'
PS1_2='$(parse_git_branch)'
PS1_3='\n\$ '
PS1="${PS1_1}${PS1_2}${PS1_3}"
# --------------------------------------------------
# Save history after each command
PROMPT_COMMAND='history -a'
# Add timestamps to the command history
export HISTTIMEFORMAT="%y-%m-%d %T "
# Unlimited history!
HISTSIZE=
HISTFILESIZE=
EOT
# --------------------------------------------------
# /root/.inputrc
# --------------------------------------------------
cat <<"EOT" > /root/.inputrc
# Include the system-wide inputrc configuration
# On Ubuntu, having ~/.inputrc automatically disables it
$include /etc/inputrc
# Make autocomplete case-insensitive
set completion-ignore-case On
# Display all possible matches for an ambiguous pattern at the first <Tab> press
set show-all-if-ambiguous on
EOT
# --------------------------------------------------
# /root/.vimrc
# --------------------------------------------------
cat <<"EOT" > /root/.vimrc
set nocompatible
"----------------------------------------
" Vim-Plug initialization
"----------------------------------------
if empty(glob('~/.vim/autoload/plug.vim'))
silent !curl -fLo ~/.vim/autoload/plug.vim --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
autocmd VimEnter * PlugInstall --sync | source $MYVIMRC
endif
call plug#begin('~/.vim/plugged')
Plug 'itchyny/lightline.vim'
Plug 'itchyny/vim-gitbranch'
call plug#end()
" Show current git branch inside lightline
let g:lightline = {
\ 'active': {
\ 'left': [ [ 'mode', 'paste' ],
\ [ 'gitbranch', 'readonly', 'filename', 'modified' ] ]
\ },
\ 'component_function': {
\ 'gitbranch': 'gitbranch#name'
\ },
\ }
" -- INSERT -- is unnecessary anymore because the mode information is displayed in the statusline.
set noshowmode
"----------------------------------------
" Other settings
"----------------------------------------
set encoding=utf-8 " encoding
set background=dark " otherwise you can't read the comments...
set tabstop=4
set softtabstop=4
set shiftwidth=4
set shiftround " indent always with a multiple of shiftwidth
set autoindent
set hidden " hides buffers instead of closing them
set backspace=indent,eol,start " allow backspacing over everything in insert mode
set number " show line numbers
set showmatch " show matching parenthesis
set ignorecase " ignore case when searching
set smartcase " ignore case if search pattern is all lowercase, case sensitive otherwise
set hlsearch " highlight search matches
set incsearch " search as-you-type
set history=1000 " remember more commands and search history
set undolevels=1000 " everybody screws up sometimes
set visualbell " don't beep
set noerrorbells " again, don't beep
set title " change the terminal title
set term=xterm-256color " tmux and vim do not play nicely without this setting
set nobackup " there are better ways to protect against data loss
set noswapfile " see before
set showcmd " show (partial) command in status line
set laststatus=2 " always display status line
"set statusline=%F%m%r%h%w\ [FORMAT=%{&ff}]\ [TYPE=%Y]\ [POS=%l,%v][%p%%]\ [BUFFER=%n]\ %{strftime('%c')}
set matchpairs+=<:> " highlight matching pairs of chars. Use the '%' character to jump between them
set paste " activate paste mode by default
EOT
# --------------------------------------------------
# /root/apache2_create_vhost.sh
# --------------------------------------------------
cat <<"CONTENT" > /root/apache2_create_vhost.sh
#!/bin/bash
#
# ------------------------------------------------------------
# Author: Enrico Boldori
# Description: Apache VirtualHost creation script
#
# Script function:
# This script helps in creating an Apache VirtualHost.
# The DocumentRoot is set to ${VHOST}/current/public to help
# when deploying a Deployer-based PHP project.
# ------------------------------------------------------------
if [ $# -ne 1 ]
then
echo "Usage: $0 vHostName"
exit 1
fi
VHOST=$1
VHOST_FILENAME="/etc/apache2/sites-available/${VHOST}.conf"
SERVERADMIN="admin@servonet.it"
# Se il file di configurazione è già esistente termino lo script
if [ -e ${VHOST_FILENAME} ]
then
echo "Il file ${VHOST_FILENAME} esiste, NON lo sovrascrivo."
exit 1
fi
# Se la cartella del VirtualHost sotto /var/www esiste, termino lo script
if [ -d /var/www/${VHOST} ]
then
echo "La cartella /var/www/${VHOST} esiste, operazione annullata."
exit 1
fi
# Devo creare il file di configurazione di apache sotto la cartella /etc/apache2/sites-available
cat >> ${VHOST_FILENAME} <<EOT
<VirtualHost *:80>
ServerAdmin ${SERVERADMIN}
DocumentRoot /var/www/${VHOST}/current/public
ServerName ${VHOST}
ErrorLog \${APACHE_LOG_DIR}/error_${VHOST}.log
CustomLog \${APACHE_LOG_DIR}/access_${VHOST}.log vhost_combined
# E_ALL
php_value error_reporting -1
php_value display_errors 0
php_value log_errors 1
php_admin_value open_basedir /tmp/:/var/tmp/:/var/www/${VHOST}/
</VirtualHost>
EOT
# Creo la cartella dove risiederanno i files del VirtualHost
mkdir -p /var/www/${VHOST}/
# Ne imposto il proprietario a root
chown root:root /var/www/${VHOST} -R
# Imposto i permessi corretti
find /var/www/${VHOST} -type d -exec chmod 755 {} \;
find /var/www/${VHOST} -type f -exec chmod 644 {} \;
# Abilito il VirtualHost
a2ensite ${VHOST}.conf
# Ricarico il servizio di Apache
service apache2 reload
echo "Apache2 reloaded"
CONTENT
# --------------------------------------------------
# /root/apache2_delete_vhost.sh
# --------------------------------------------------
cat <<"CONTENT" > /root/apache2_delete_vhost.sh
#!/bin/bash
#
# ------------------------------------------------------------
# Author: Enrico Boldori
# Description: Apache VirtualHost deletion script
#
# Script function:
# This script helps in deleting an Apache VirtualHost.
# ------------------------------------------------------------
if [ $# -ne 1 ]
then
echo "Usage: $0 vHostName"
exit 1
fi
VHOST=$1
VHOST_FILENAME="/etc/apache2/sites-available/${VHOST}.conf"
VHOST_FOLDER="/var/www/${VHOST}/"
# Disabilito il VirtualHost
a2dissite ${VHOST}
service apache2 reload
echo "VirtualHost disattivato."
# Elimino il file di configurazione
CHOICE="n"
echo -n "Eliminare il file di configurazione (${VHOST_FILENAME}) [y/n]? "
read CHOICE
if [ ${CHOICE} == "y" ]
then
rm ${VHOST_FILENAME}
fi
# Mostro il listing della directory prima di eliminarla
echo "+-------------------------------------------------+"
echo "| VirtualHost directory listing |"
echo "+-------------------------------------------------+"
echo ""
ls -lha ${VHOST_FOLDER}
if [ -d "${VHOST_FOLDER}/html" ]
then
echo "+-------------------------------------------------+"
echo "| VirtualHost directory listing (/html folder) |"
echo "+-------------------------------------------------+"
echo ""
ls -lha "${VHOST_FOLDER}/html"
fi
# Elimino la cartella del virtualhost
CHOICE="n"
echo "+-------------------------------------------------+"
echo "| ATTENZIONE! |"
echo "+-------------------------------------------------+"
echo ""
echo "Il prossimo comando può essere fatale."
echo ""
echo "Controllare attentamente il percorso mostrato."
echo -n "Eliminare la cartella contenente i dati (${VHOST_FOLDER}) [y/n]? "
read CHOICE
if [ ${CHOICE} == "y" ]
then
rm -rvf ${VHOST_FOLDER}
fi
echo "VirtualHost eliminato"
CONTENT
# --------------------------------------------------
# /root/mysql_create_database_with_user.sh
# --------------------------------------------------
cat <<"CONTENT" > /root/mysql_create_database_with_user.sh
#!/bin/bash
#
# ------------------------------------------------------------
# Author: Enrico Boldori
# Description: MySQL database and user creation script
#
# Script function:
# This script helps in creating a database with its associated
# user, with a reasonable set of permissions.
# ------------------------------------------------------------
#!/bin/bash
# Script per creare automaticamente un database con l'utente associato
if [ $# -ne 2 ]
then
echo "Utilizzo: $0 database_name username"
exit 1
fi
DATABASE="$1"
USERNAME="$2"
read -s -p "Inserisci la password per l'utente ${USERNAME}: " PASSWORD
echo
if [ -z ${PASSWORD} ]
then
echo "Password vuota non concessa.";
exit 1
fi
# Definizione delle query
DATABASE_QUERY="CREATE DATABASE ${DATABASE} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
USER_QUERY="CREATE USER '${USERNAME}'@'localhost' IDENTIFIED BY '${PASSWORD}';"
PERM_QUERY="GRANT ALL PRIVILEGES ON ${DATABASE}.* TO '${USERNAME}'@'localhost';"
# Esecuzione delle query
/usr/bin/mysql -u root -p -e "${DATABASE_QUERY};${USER_QUERY};${PERM_QUERY};"
CONTENT
# --------------------------------------------------
# /root/mysql_backup.sh
# --------------------------------------------------
cat <<"CONTENT" > /root/mysql_backup.sh
#!/bin/bash
#
# ------------------------------------------------------------
# Author: Enrico Boldori
# Description: MySQL backup script
#
# Script function:
# This script uses mysqldump to automatically backup each MySQL database, excluding system-related
# ones (sys, mysql, information_schema, performance_schema).
#
# Backups are automatically rotated, keeping the last 6 hours backups under the daily folder.
# If today's daily backup has not been created yet, the hourly backup gets copied under the daily folder.
# Daily backups are retained for 8 days.
# If the current day is a Sunday, today's backup is copied under the weekly folder.
# If the current day is the first day of the month, today's backup is copied under the monthly folder.
#
# This script should be configured to use a credentials file with the following content:
#
# [client]
# user = backup user's username
# password = backup user's password
#
# To prevent anyone from reading the credentials file, its permissions should be set to 400.
#
# This user should be granted the following permissions:
# CREATE USER 'backup'@'localhost' IDENTIFIED BY 'Some complex password here';
# GRANT SELECT, LOCK TABLES ON *.* TO 'backup'@'localhost';
#
# Finally, this script should be added to the crontab file (crontab -e) with the following line:
# 0 */4 * * * /root/mysql_backup.sh
# ------------------------------------------------------------
# Backup configuration
BACKUP_DIR="/var/www/mysqldump"
CREDENTIALS_FILE="/root/.mysql_backup_credentials"
BACKUP_DIR_HOURLY="${BACKUP_DIR}/hourly"
BACKUP_DIR_DAILY="${BACKUP_DIR}/daily"
BACKUP_DIR_WEEKLY="${BACKUP_DIR}/weekly"
BACKUP_DIR_MONTHLY="${BACKUP_DIR}/monthly"
# Define commands
MYSQLDUMP="/usr/bin/mysqldump --defaults-extra-file=${CREDENTIALS_FILE} --add-drop-database --add-drop-table --hex-blob --single-transaction --skip-lock-tables --no-tablespaces"
MYSQLSHOW="/usr/bin/mysqlshow --defaults-extra-file=${CREDENTIALS_FILE}"
# Create the backup folders if they do not exist
mkdir -p "${BACKUP_DIR}"
mkdir -p "${BACKUP_DIR_HOURLY}"
mkdir -p "${BACKUP_DIR_DAILY}"
mkdir -p "${BACKUP_DIR_WEEKLY}"
mkdir -p "${BACKUP_DIR_MONTHLY}"
chmod 700 "${BACKUP_DIR}"
chmod 700 "${BACKUP_DIR_HOURLY}"
chmod 700 "${BACKUP_DIR_DAILY}"
chmod 700 "${BACKUP_DIR_WEEKLY}"
chmod 700 "${BACKUP_DIR_MONTHLY}"
# List all the databases
DATABASES=$(${MYSQLSHOW} | head -n -1 | tail -n +4 | tr -d " |")
# Generate a timestamp in the format YYYY-MM-DD
TODAY=$(date +\%F)
# Get the day of week (1..7, 1 is Monday) and day of month (1..31)
DAY_OF_WEEK=$(date +\%u)
DAY_OF_MONTH=$(date +\%d)
# Get the current time
CURRENT_TIME=$(date +\%H-\%M)
# Delete old database dumps
find "${BACKUP_DIR_HOURLY}" -type f -name "*.sql.gz" -mmin +1470 -delete
find "${BACKUP_DIR_DAILY}" -type f -name "*.sql.gz" -mtime +6 -delete
find "${BACKUP_DIR_WEEKLY}" -type f -name "*.sql.gz" -mtime +27 -delete
find "${BACKUP_DIR_MONTHLY}" -type f -name "*.sql.gz" -mtime +365 -delete
# Dump each database
for DATABASE in ${DATABASES}; do
# Exclude certain databases from the dump
if [ "${DATABASE}" == "" ]; then continue; fi
if [ "${DATABASE}" == "sys" ]; then continue; fi
if [ "${DATABASE}" == "mysql" ]; then continue; fi
if [ "${DATABASE}" == "information_schema" ]; then continue; fi
if [ "${DATABASE}" == "performance_schema" ]; then continue; fi
# Dump the hourly database
HOURLY_DATABASE_DUMP_NAME="${DATABASE}_${TODAY}_${CURRENT_TIME}.sql.gz"
HOURLY_DATABASE_DUMP_FILE="${BACKUP_DIR_HOURLY}/${HOURLY_DATABASE_DUMP_NAME}"
${MYSQLDUMP} "${DATABASE}" | gzip -9 -c > "${HOURLY_DATABASE_DUMP_FILE}"
# Ensure that only root can read the dumped file
chmod 400 "${HOURLY_DATABASE_DUMP_FILE}"
# Copy it under the DAILY folder if it does not already exist
DAILY_DATABASE_DUMP_NAME="${DATABASE}_${TODAY}.sql.gz"
DAILY_DATABASE_DUMP_FILE="${BACKUP_DIR_DAILY}/${DAILY_DATABASE_DUMP_NAME}"
if [ -f "${DAILY_DATABASE_DUMP_FILE}" ]; then continue; fi
ln "${HOURLY_DATABASE_DUMP_FILE}" "${BACKUP_DIR_DAILY}/${DAILY_DATABASE_DUMP_NAME}";
# If on a Sunday, copy the backup to the weekly folder
if [ ${DAY_OF_WEEK} -eq 7 ]; then ln "${DAILY_DATABASE_DUMP_FILE}" "${BACKUP_DIR_WEEKLY}/${DAILY_DATABASE_DUMP_NAME}"; fi
# If on the first day of the month, copy the backup to the monthly folder
if [ ${DAY_OF_MONTH} -eq 1 ]; then ln "${DAILY_DATABASE_DUMP_FILE}" "${BACKUP_DIR_MONTHLY}/${DAILY_DATABASE_DUMP_NAME}"; fi
done
CONTENT
# --------------------------------------------------
# Install and configure the LAMP stack
# --------------------------------------------------
tasksel install lamp-server
a2enmod expires cache rewrite headers
# /etc/apache2/apache2.conf
sed -i 's/Options Indexes FollowSymLinks/Options -Indexes +FollowSymLinks/' /etc/apache2/apache2.conf
# !b negates the previous address (regexp) and breaks out of any processing, ending the sed commands
# n prints the current line and then reads the next into the pattern space,
# c changes the current line to the string following the command
# See https://stackoverflow.com/questions/18620153/find-matching-text-and-replace-next-line
sed -i '/^\tOptions -Indexes +FollowSymLinks/!b;n;c\\tAllowOverride All' /etc/apache2/apache2.conf
# /etc/apache2/conf-available/security.conf
sed -i 's/^ServerTokens/#ServerTokens/' /etc/apache2/conf-available/security.conf
sed -i '/^# where Full conveys the most information, and Prod the least./a ServerTokens Prod' /etc/apache2/conf-available/security.conf
sed -i 's/^ServerSignature On/ServerSignature Off/' /etc/apache2/conf-available/security.conf
sed -i '/^#<\/DirectoryMatch>/a <DirectoryMatch "\/\\.svn">\n\tRequire all denied\n<\/DirectoryMatch>\n\n<DirectoryMatch "\/\\.git">\n\tRequire all denied\n<\/DirectoryMatch>\n\n<Files ".git*">\n\tRequire all denied\n<\/Files>\n' /etc/apache2/conf-available/security.conf
service apache2 restart
wget https://github.com/vrana/adminer/releases/download/v4.8.1/adminer-4.8.1-mysql-en.php -O /var/www/html/adminer.php
wget https://raw.githubusercontent.com/vrana/adminer/master/designs/pepa-linha/adminer.css -O /var/www/html/adminer.css
# Install certbot through SNAP
snap install core
snap refresh core
snap install --classic certbot
ln -s /snap/bin/certbot /usr/bin/certbot
# --------------------------------------------------
# Configure MySQL backup
# --------------------------------------------------
MYSQL_BACKUP_PASSWORD=$(pwgen -cnsB 20 1)
cat <<EOT > /root/.mysql_backup_credentials
[client]
user = backup
password = ${MYSQL_BACKUP_PASSWORD}
EOT
chmod 400 /root/.mysql_backup_credentials
mysql -u root -e "CREATE USER backup@localhost IDENTIFIED BY '${MYSQL_BACKUP_PASSWORD}';"
mysql -u root -e "GRANT SELECT, LOCK TABLES ON *.* TO 'backup'@'localhost';"
chmod 700 /root/*.sh
# --------------------------------------------------
# Disable MySQL binary logging (enabled by default in certain versions)
# --------------------------------------------------
echo "Disabling binary logging, re-enable it if needed by editing /etc/mysql/mysql.conf.d/mysqld.cnf"
echo disable_log_bin >> /etc/mysql/mysql.conf.d/mysqld.cnf
# --------------------------------------------------
# Enable MySQL's PID file (useful for tracking its status through monit)
# --------------------------------------------------
sed -i 's/# pid-file/pid-file/' /etc/mysql/mysql.conf.d/mysqld.cnf
# --------------------------------------------------
# Enable MySQL's slow query log
# --------------------------------------------------
sed -i 's/# slow_query_log/slow_query_log/' /etc/mysql/mysql.conf.d/mysqld.cnf
sed -i 's/# long_query_time/long_query_time/' /etc/mysql/mysql.conf.d/mysqld.cnf
# --------------------------------------------------
service mysql restart
# --------------------------------------------------
# Configure PHP
# --------------------------------------------------
apt install -y software-properties-common
yes | add-apt-repository ppa:ondrej/php
apt update && apt upgrade -y
update-alternatives --set php /usr/bin/php7.4
update-alternatives --set phar /usr/bin/phar7.4
update-alternatives --set phar.phar /usr/bin/phar.phar7.4
apt install -y php7.4-curl php7.4-xml php7.4-zip php7.4-mbstring php7.4-gd php7.4-mysql php7.4-imagick
phpenmod curl xml zip mbstring gd mysql imagick
wget https://getcomposer.org/installer -O composer-setup.php
php -f composer-setup.php
if [ -f composer.phar ]; then
mv composer.phar /usr/bin/composer
else
echo "WARNING: Could not setup composer"
fi
rm composer-setup.php
# --------------------------------------------------
# Install and configure Munin
# --------------------------------------------------
apt install -y munin munin-node libwww-perl libdbi-perl libcache-cache-perl libdbd-mysql-perl
ln -s /usr/share/munin/plugins/apache_* /etc/munin/plugins/
ln -s /usr/share/munin/plugins/mysql_* /etc/munin/plugins/
sed -i "s/localhost.localdomain/$1/" /etc/munin/munin.conf
cat <<EOT > /etc/munin/plugin-conf.d/df
[df]
env.exclude none unknown rootfs iso9660 squashfs udf romfs ramfs debugfs cgroup_root devtmpfs tmpfs
EOT
cat <<EOT > /etc/munin/plugin-conf.d/diskstats
[diskstats]
env.include_only /dev/sda
EOT
# Disable some plugins
rm /etc/munin/plugins/irqstats
rm /etc/munin/plugins/mysql_bin*
# Enable Apache's CGI module, to use Munin's graph zoom feature
a2enmod cgi
# --------------------------------------------------
# Restart Munin
# --------------------------------------------------
service munin-node restart
# --------------------------------------------------
# Restart Apache
# --------------------------------------------------
service apache2 restart
# --------------------------------------------------
# Install and configure Monit
# --------------------------------------------------
apt install -y monit
cp /etc/monit/monitrc /etc/monit/monitrc.original
cat <<"CONTENT" > /etc/monit/monitrc
set daemon 60 with start delay 60
set log /var/log/monit.log
set idfile /var/lib/monit/id
set statefile /var/lib/monit/state
set eventqueue basedir /var/lib/monit/events slots 100
set mailserver MONIT_SMTP_HOST port 587 username MONIT_SMTP_USERNAME password MONIT_SMTP_PASSWORD using tlsv13
set alert MONIT_SMTP_RECIPIENT
# --------------------------------------------------
check system $HOST
if loadavg (1min) > 4 then alert
if loadavg (5min) > 2 then alert
if cpu usage > 95% for 3 cycles then alert
if memory usage > 75% for 3 cycles then alert
# --------------------------------------------------
check process apache with pidfile /var/run/apache2/apache2.pid
start program = "/bin/systemctl start apache2" with timeout 60 seconds
stop program = "/bin/systemctl stop apache2"
if cpu > 80% for 2 cycles then alert
if cpu > 90% for 10 cycles then alert
check process mysql with pidfile /var/run/mysqld/mysqld.pid
start program = "/bin/systemctl start mysql" with timeout 60 seconds
stop program = "/bin/systemctl stop mysql"
if cpu > 80% for 2 cycles then alert
if cpu > 90% for 10 cycles then alert
check process ssh with pidfile /var/run/sshd.pid
start program = "/bin/systemctl start ssh" with timeout 60 seconds
stop program = "/bin/systemctl stop ssh"
# --------------------------------------------------
check filesystem rootfs with path /dev/sda1
if space usage > 85% for 10 cycles then alert
if space usage > 90% for 5 cycles then alert
if space usage > 95% for 2 cycles then alert
# --------------------------------------------------
include /etc/monit/conf.d/*
include /etc/monit/conf-enabled/*
CONTENT
echo "--------------------------------------------------"
echo "REMEMBER TO: Schedule MySQL backup script (crontab -e -> 0 */4 * * * /root/mysql_backup.sh)"
echo "REMEMBER TO: Allow Munin access from your IP (under /etc/munin/apache24.conf)"
echo "REMEMBER TO: Configure Monit's SMTP credentials (under /etc/monit/monitrc)"
echo "--------------------------------------------------"