Simple Server Monitor Bot - Telegram + PHP
Publicado por Rodrigo Leutz em 16/01/2019
[ Hits: 7.715 ]
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);
?>
Som no Linux (recompilando kernel)
Slackware 12 com ipw3945 + wpa-psk
Copiando e colando texto da web sem formatação
Apache 2 + Debian 3.1 + DocumentRoot
Como verificar a integridade dos arquivos baixados usando cksfv
Instalando KDE 3.3 no Mandrake 10
Usando o browser como visualizador de imagens
Cirurgia para acelerar o openSUSE em HD externo via USB
Void Server como Domain Control
Modo Simples de Baixar e Usar o bash-completion
Monitorando o Preço do Bitcoin ou sua Cripto Favorita em Tempo Real com um Widget Flutuante
[Resolvido] VirtualBox can't enable the AMD-V extension
Como verificar a saúde dos discos no Linux
Como instalar , particionar, formatar e montar um HD adicional no Linux?
Como automatizar sua instalação do Ubuntu para desenvolvimento de software.
Fiz uma pergunta no fórum mas não consigo localizar (13)
Quais os códigos mais dificeis que vcs sabem fazer? (2)
Não consigo instalar distro antiga no virtualbox nem direto no hd (7)
Servidor Ubuntu 24.04 HD 500 não tenho espaço na \home\adminis... [RES... (8)
Dá para criar um bom jogo usando a linguagem de programação C? [RESOLV... (1)









