Simple Server Monitor Bot - Telegram + PHP
Publicado por Rodrigo Leutz em 16/01/2019
[ Hits: 7.550 ]
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
Som no Linux (recompilando kernel)
rc.local na systemd - script de execução na inicialização do sistema
Deixe o Gnome com a cara do XP
Google Earth 5.0 - Warning: Unable to create prefs directory
Horários diferentes? A culpa é do "UTC"
Comparação entre os escalonadores BFQ e MQ-Deadline (acesso a disco) no Arch e Debian
Conciliando o uso da ZRAM e SWAP em disco na sua máquina
Servidor de Backup com Ubuntu Server 24.04 LTS, RAID e Duplicati (Dell PowerEdge T420)
Visualizar câmeras IP ONVIF no Linux sem necessidade de instalar aplicativos
Converter os repositórios Debian para o novo formato com as chaves
Instalando Spotify no Debian 13
Realizar overclock no Miyoo Mini (plus ou normal)
linux mint reconhece microfone de lapela como fone de ouvido sem micro... (5)
E aí? O Warsaw já está funcionando no Debian 13? (2)
Dúvidas sobre a originalidade de conteúdos online (12)