Created
June 25, 2025 14:36
-
-
Save tcha-tcho/fc7ae6556282c1e15c2195665f6cda9d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Executar script de monitoramento de website a cada 5 minutos | |
*/5 * * * * /caminho/para/website_monitor.sh > /dev/null 2>&1 | |
# precisa de permissão | |
chmod +x /caminho/para/website_monitor.sh | |
# configurações para o ssh | |
ssh-keygen -t rsa -b 4096 | |
ssh-copy-id usuario@servidor_remoto | |
# se não tiver iniciado | |
crontab -e |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Script Avançado de Monitoramento de Website e Reinicialização de Serviço Remoto | |
# Este script verifica se um website está respondendo e, se não estiver, | |
# conecta-se a um servidor remoto via SSH para reiniciar um serviço | |
# Configuração - MODIFIQUE ESTES VALORES | |
WEBSITE_URL="http://example.com" # URL para monitorar | |
CHECK_INTERVAL=5 # Tempo entre verificações em minutos | |
MAX_RETRIES=3 # Número de tentativas antes de tomar ação | |
RETRY_DELAY=30 # Segundos entre tentativas | |
TIMEOUT=10 # Timeout do curl em segundos | |
REMOTE_SERVER="user@remote_server" # String de conexão SSH (usuário@servidor) | |
REMOTE_SERVICE="apache2" # Serviço para reiniciar no servidor remoto | |
LOG_FILE="/var/log/website_monitor.log" # Localização do arquivo de log | |
SEND_EMAIL=true # Se deve enviar notificações por email | |
EMAIL_RECIPIENT="[email protected]" # Destinatário do email para notificações | |
# Função para verificar disponibilidade do website | |
check_website() { | |
# Obter código de status HTTP usando curl com timeout | |
HTTP_STATUS=$(curl -s -m "$TIMEOUT" -o /dev/null -w "%{http_code}" "$WEBSITE_URL") | |
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S") | |
# Verificar se o código de status é 200 (OK) | |
if [ "$HTTP_STATUS" -eq 200 ]; then | |
echo "$TIMESTAMP - Website $WEBSITE_URL está ONLINE (Status: $HTTP_STATUS)" >> "$LOG_FILE" | |
return 0 | |
else | |
echo "$TIMESTAMP - Website $WEBSITE_URL está OFFLINE (Status: $HTTP_STATUS)" >> "$LOG_FILE" | |
return 1 | |
fi | |
} | |
# Função para enviar notificação por email | |
send_notification() { | |
local subject="$1" | |
local message="$2" | |
if [ "$SEND_EMAIL" = true ]; then | |
echo "$message" | mail -s "$subject" "$EMAIL_RECIPIENT" | |
echo "$(date "+%Y-%m-%d %H:%M:%S") - Notificação por email enviada para $EMAIL_RECIPIENT" >> "$LOG_FILE" | |
fi | |
} | |
# Função para reiniciar serviço no servidor remoto | |
restart_remote_service() { | |
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S") | |
echo "$TIMESTAMP - Tentando reiniciar $REMOTE_SERVICE em $REMOTE_SERVER" >> "$LOG_FILE" | |
# Executar comando SSH para reiniciar o serviço | |
ssh -o ConnectTimeout=30 "$REMOTE_SERVER" "sudo systemctl restart $REMOTE_SERVICE" | |
# Verificar se o comando SSH foi bem-sucedido | |
if [ $? -eq 0 ]; then | |
echo "$TIMESTAMP - Reiniciado com sucesso $REMOTE_SERVICE em $REMOTE_SERVER" >> "$LOG_FILE" | |
send_notification "Serviço Reiniciado: $REMOTE_SERVICE" "O serviço $REMOTE_SERVICE em $REMOTE_SERVER foi reiniciado com sucesso às $TIMESTAMP após o website $WEBSITE_URL ser detectado como offline." | |
return 0 | |
else | |
echo "$TIMESTAMP - Falha ao reiniciar $REMOTE_SERVICE em $REMOTE_SERVER" >> "$LOG_FILE" | |
send_notification "URGENTE: Falha ao Reiniciar Serviço" "Falha ao reiniciar $REMOTE_SERVICE em $REMOTE_SERVER às $TIMESTAMP. Intervenção manual necessária." | |
return 1 | |
fi | |
} | |
# Função para verificar se o serviço está funcionando após reinicialização | |
verify_service() { | |
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S") | |
echo "$TIMESTAMP - Verificando se o website está online após reinicialização do serviço" >> "$LOG_FILE" | |
# Aguardar um pouco para o serviço iniciar completamente | |
sleep 30 | |
# Verificar se o website está respondendo | |
if check_website; then | |
echo "$TIMESTAMP - Website está online após reinicialização do serviço" >> "$LOG_FILE" | |
send_notification "Website Restaurado" "Website $WEBSITE_URL está online novamente após reinicialização do serviço às $TIMESTAMP." | |
return 0 | |
else | |
echo "$TIMESTAMP - Website ainda está offline após reinicialização do serviço" >> "$LOG_FILE" | |
send_notification "URGENTE: Website Ainda Offline" "Website $WEBSITE_URL ainda está offline após reinicialização do serviço às $TIMESTAMP. Intervenção manual necessária." | |
return 1 | |
fi | |
} | |
# Função principal | |
main() { | |
# Criar diretório de log se não existir | |
mkdir -p "$(dirname "$LOG_FILE")" | |
# Registrar início do script | |
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S") | |
echo "$TIMESTAMP - Script de monitoramento de website iniciado" >> "$LOG_FILE" | |
# Verificar website com tentativas | |
for ((i=1; i<=MAX_RETRIES; i++)); do | |
if check_website; then | |
# Website está online, sair com sucesso | |
exit 0 | |
else | |
echo "$TIMESTAMP - Tentativa $i de $MAX_RETRIES" >> "$LOG_FILE" | |
# Se esta for a última tentativa, tomar ação | |
if [ $i -eq $MAX_RETRIES ]; then | |
send_notification "Alerta de Website Offline" "Website $WEBSITE_URL está offline. Tentando reiniciar serviço $REMOTE_SERVICE em $REMOTE_SERVER." | |
# Reiniciar o serviço | |
if restart_remote_service; then | |
# Verificar se o website está online novamente | |
verify_service | |
fi | |
else | |
# Aguardar antes da próxima tentativa | |
sleep $RETRY_DELAY | |
fi | |
fi | |
done | |
} | |
# Executar a função principal | |
main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment