Simple Server Monitor Bot - Telegram + PHP
Publicado por Rodrigo Leutz em 16/01/2019
[ Hits: 7.167 ]
Blog: https://uware.com.br
<?php class Logs{ private $pdo; public function __construct(){ try{ $this->pdo = new PDO("mysql:dbname=uwarebot;host=localhost","uwarebot","<sua senha>"); }catch(PDOException $e){ echo "Erro na db: ".$e->getMessage(); } } public function log($user_id,$name,$action) { $sql = $this->pdo->prepare("insert into logs (data,user_id,name,action) values (NOW(),:user_id,:name,:action)"); $sql->bindValue(':user_id',$user_id); $sql->bindValue(':name',$name); $sql->bindValue(':action',$action); $sql->execute(); return true; } public function showLog(){ $sql = $this->pdo->prepare("select * from logs order by id desc limit 20;"); $sql->execute(); if($sql->rowCount()>0){ return $sql->fetchAll(); } else{ return array(); } } public function showAllLog(){ $sql = $this->pdo->prepare("select * from logs order by id desc;"); $sql->execute(); if($sql->rowCount()>0){ return $sql->fetchAll(); } else{ return array(); } } } ?>
<?php /* Autor: Rodrigo Leutz Telegram Bot: Simple Server Monitor */ // Ip do servidor, se não for a msg dele ja sai // Verifique nos logs do nginx if($_SERVER['REMOTE_ADDR']!='149.154.167.217'){ exit; } // Classe de logs require "class.logs.php"; // Aqui é o token e user id do telegram define('BOT_TOKEN', '<token>'); define('OWNER','<user id>'); define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/'); // Iniciando a class do Log $log = new Logs(); // Variaveis $content = file_get_contents("php://input"); $update = json_decode($content, true); $chatID = $update["message"]["chat"]["id"]; $text_inteiro = $update['message']['text']; $first_name = $update['message']['from']['first_name']; $last_name = $update['message']['from']['last_name']; $first_name = $first_name." ".$last_name; // Programação do uwareBot $text = explode(' ',$text_inteiro); // Comandos do dono if($update['message']['from']['id'] == OWNER){ if($text[0] == '/failssh'){ $msg = shell_exec("/usr/bin/sudo fail2ban-client status sshd"); $log->log($update['message']['from']['id'],$first_name,$text_inteiro); } else if($text[0] == '/free'){ $msg = shell_exec("free -m"); $log->log($update['message']['from']['id'],$first_name,$text_inteiro); } else if($text[0] == '/last'){ $msg = shell_exec("last -20"); $log->log($update['message']['from']['id'],$first_name,$text_inteiro); } else if($text[0] == '/log'){ $list = $log->showLog(); $msg = "id - Data - User_id - Name - Action"; foreach ($list as $key) { $retorno = "\n".$key['id']." - ".$key['data']." - ".$key['user_id']." - ".$key['name']." - ".$key['action']; $msg.= $retorno; } $log->log($update['message']['from']['id'],$first_name,$text_inteiro); } else if($text[0] == '/logall'){ $list = $log->showAllLog(); $msg = "id - Data - User_id - Name - Action"; foreach ($list as $key) { $retorno = "\n".$key['id']." - ".$key['data']." - ".$key['user_id']." - ".$key['name']." - ".$key['action']; $msg.= $retorno; } $log->log($update['message']['from']['id'],$first_name,$text_inteiro); } else if($text[0] == '/ls'){ $msg = shell_exec("/usr/bin/sudo ls -lh $text[1]"); $log->log($update['message']['from']['id'],$first_name,$text_inteiro); } else if($text[0] == '/ngerror'){ $msg = shell_exec("/usr/bin/sudo tail /var/log/nginx/error.log"); $log->log($update['message']['from']['id'],$first_name,$text_inteiro); } else if($text[0] == '/ps'){ $msg = shell_exec("ps aux | grep $text[1]"); $log->log($update['message']['from']['id'],$first_name,$text_inteiro); } else if($text[0] == '/sshlog'){ $msg = shell_exec("/usr/bin/sudo journalctl -u sshd --no-pager -n 20"); $log->log($update['message']['from']['id'],$first_name,$text_inteiro); } else if($text[0] == '/top'){ $msg = shell_exec("/usr/bin/sudo top -b -n 1 | head -n 15"); $log->log($update['message']['from']['id'],$first_name,$text_inteiro); } else if($text[0] == '/uptime'){ $msg = shell_exec("uptime"); $log->log($update['message']['from']['id'],$first_name,$text_inteiro); } else if($text[0] == '/version'){ $msg = shell_exec("uname -a"); $log->log($update['message']['from']['id'],$first_name,$text_inteiro); } else if($text[0] == '/versions'){ $cen = shell_exec("cat /etc/redhat-release"); $des = shell_exec("ls -lct --time-style=+\"%F %T\" / | tail -1 | awk '{print $6, $7}'"); $php = phpversion(); $mys = shell_exec("mysql -V"); $msg = "S.O.: $cen $des"; $msg.= "PHP: $php"; $msg.= "\nMySQL: $mys"; $log->log($update['message']['from']['id'],$first_name,$text_inteiro); } else if($text[0] == '/w'){ $msg = shell_exec("w"); $log->log($update['message']['from']['id'],$first_name,$text_inteiro); } /* Escopo de função de dono else if($text[0] == ''){ $msg = shell_exec(""); $log->log($update['message']['from']['id'],$first_name,$text_inteiro); } */ } // Funções de todos os usuários if($text[0] == '/help'){ $msg = "Comandos do uwareBot:\n\n"; if($update['message']['from']['id'] == OWNER){ $msg.= "/failssh --> falhas no sshd do fail2ban\n"; $msg.= "/free --> Verifica memória\n"; $msg.= "/last --> Ultimos 20 logins\n"; $msg.= "/log --> Ultimos 20 logs do bot\n"; $msg.= "/logall --> Todos os logs do bot\n"; $msg.= "/ls (pasta) --> Lista o diretório\n"; $msg.= "/ngerror --> Erros do nginx\n"; $msg.= "/ps (processo) --> Lista processo\n"; $msg.= "/sshlog --> 20 ultimos logs do sshd\n"; $msg.= "/top --> Comando top\n"; $msg.= "/uptime --> Uptime do server\n"; $msg.= "/version --> Verssão do kernel\n"; $msg.= "/versions --> Outras versõe\n"; $msg.= "/w --> Quem esrá logado\n"; } $msg.= "/oi --> Saudações\n"; $msg.= "/ping (url) --> Ping no destino\n"; $msg.= "/start --> Bem vindo\n"; $msg.= "/whois (url) --> Whois do destino\n"; $log->log($update['message']['from']['id'],$first_name,$text_inteiro); } if($text[0] == '/oi'){ $msg = "oi $first_name, como vai?"; $log->log($update['message']['from']['id'],$first_name,$text_inteiro); } else if($text[0] == '/ping'){ $msg = shell_exec("/usr/bin/sudo ping $text[1] -c 4"); $log->log($update['message']['from']['id'],$first_name,$text_inteiro); } else if($text[0] == '/start'){ $msg = "Seja bem vindo ao uwareBot Server Monitor"; $log->log($update['message']['from']['id'],$first_name,$text_inteiro); } else if($text[0] == '/whois'){ $msg = shell_exec("/usr/bin/sudo whois $text[1]"); $log->log($update['message']['from']['id'],$first_name,$text_inteiro); } /* Escopo de função de qualquer um if($text[0] == ''){ $msg = shell_exec(""); $log->log($update['message']['from']['id'],$first_name,$text_inteiro); } */ // Envio para o servidor telegram $sendto =API_URL."sendmessage?chat_id=".$chatID."&text=".urlencode($msg); file_get_contents($sendto); ?>
Instalação do tigervnc com certificado SSL
Abrindo mais de um cliente Telegram
Instalando Placa Nvidia no Fedora Core 27
Comprimindo arquivos PDF no Nautilus
Opção "editar como root" no botão direito do mouse no KDE
Novo YaST - Para os amantes do SuSE Linux
Atenção a quem posta conteúdo de dicas, scripts e tal (6)
Como Configurar um Túnel SSH Reverso para Acessar Sua Máquina Local a Partir de uma Máquina Remota
Configuração para desligamento automatizado de Computadores em um Ambiente Comercial
O mínimo que você precisa saber sobre o terminal (parte 2)
O mínimo que você precisa saber sobre o terminal (parte 1)
Como iniciar uma máquina virtual do VirtualBox automaticamente no boot do LUbuntu 18 LTS
Mudar o gerenciador de login (GDM para SDDM e vice-versa) - parte 2
Como deixar as abas do Firefox mais fininhas
Mudar o gerenciador de login (GDM para SDDM)
"Tentando" fazer com que programas rodem no Wayland e no X11
Como baixar os drivers de áudio no linux mint? (7)
Como posso localizar o arquivo HTML da página inicial do GLPI dentro d... (2)
O que você está ouvindo agora? [2] (164)
Erro ao iniciar Ubuntu 24.04.1 LTS - Management Owner Key - MoK (6)
[Python] Automação de scan de vulnerabilidades
[Python] Script para analise de superficie de ataque
[Shell Script] Novo script para redimensionar, rotacionar, converter e espelhar arquivos de imagem
[Shell Script] Iniciador de DOOM (DSDA-DOOM, Doom Retro ou Woof!)
[Shell Script] Script para adicionar bordas às imagens de uma pasta