Shell script para reiniciar automaticamente Apache, Nginx ou MySQL quando serviços cairem

É comum serviços Apache, Nginx ou MySQL caírem. Então criei o shell script abaixo para reiniciar esses serviços automaticamente sem depender da minha interação manual. Para ajudar ele encaminha uma notificação ao Slack para alertar. Assim se o serviço cair repetidas vezes, é bom dar uma conferida.

Basta configurar ele no Crontab conforme o código comentado. Para receber notificações no Slack você precisa configurar um aplicativo e alterar abaixo a url em SLACK_WEBHOOK.

#!/bin/sh
# Configuração no Crontab:
# */5 * * * * cd /var/www/scripts/; ./persistente > persistente.log

SLACK_WEBHOOK="https://hooks.slack.com/services/xxxxx/xxxxx/XXXXXX"
HOSTNAME=`hostname`

# Apache
ps auxw | grep apache2 | grep -v grep > /dev/null
if [ $? != 0 ]
then
        curl -X POST -H 'Content-type: application/json' --data '{"attachments": [{"text": "Apache foi reiniciado no servidor '"$HOSTNAME"'!","thumb_url": "https://tenfen.dev/assinatura_email/silvio4.png"}]}' $SLACK_WEBHOOK
        /usr/sbin/service apache2 restart
fi

# Nginx
ps auxw | grep nginx | grep -v grep > /dev/null
if [ $? != 0 ]
then
        curl -X POST -H 'Content-type: application/json' --data '{"attachments": [{"text": "Nginx foi reiniciado no servidor '"$HOSTNAME"'!","thumb_url": "https://tenfen.dev/assinatura_email/silvio4.png"}]}' $SLACK_WEBHOOK
        /usr/sbin/service nginx restart
fi

# MySQL
ps auxw | grep mysql | grep -v grep > /dev/null
if [ $? != 0 ]
then
        curl -X POST -H 'Content-type: application/json' --data '{"attachments": [{"text": "MariaDB foi reiniciado no servidor '"$HOSTNAME"'!","thumb_url": "https://tenfen.dev/assinatura_email/silvio4.png"}]}' $SLACK_WEBHOOK
        /usr/sbin/service mysql restart
fi
silvio

Sobre Silvio Tenfen Junior

Experiência desde 2011 em Desenvolvimento Web e Sistemas. Desenvolvimento de Sites Estáticos e Auto-gerenciáveis com PHP Puro, ASP, CodeIgniter, CakePHP, Symfony, Zend, Joomla, WordPress, WooCommerce e React. Desenvolvimento de Web Services. Montagem de Lojas Virtuais Magento e WooCommerce com integração de estoque de produtos e pedidos. Integração com Pagamentos. Backup, Configuração e Manutenção de Servidores Linux (Amazon Web Services e DigitalOcean). Migração de Serviços de Hospedagem (Sites e E-mails). Atendimento ao Cliente para E-mails, Sites e Sistemas.

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

Este site utiliza o Akismet para reduzir spam. Saiba como seus dados em comentários são processados.