Simple Server Monitor Bot - Telegram + PHP

Publicado por Rodrigo Leutz em 16/01/2019

[ Hits: 7.167 ]

Blog: https://uware.com.br

 


Simple Server Monitor Bot - Telegram + PHP



Bom, resolvi fazer um server monitor com um bot do Telegram na linguagem PHP.

Dependências:
  • MySQL
  • nginx com https
  • php
  • fail2ban

Vou explicar como utilizar ele.

Primeiro crie seu bot no Telegram falando com @BotFather.

/start
/newbot


Digite o nome do seu bot e você receberá seu token, vamos utilizar o token (<token> será descrito desta maneira).

Entre em seu mysql como root:

mysql -u root -p

Crie a seguinte database, tabela e usuário:

mysql> create user 'uwarebot'@'localhost' identified by '<sua senha>';
mysql> create database uwarebot;
mysql> use uwarebot;
mysql> ALTER DATABASE `uwarebot` CHARSET = UTF8 COLLATE = utf8_general_ci;
mysql>
mysql> create table logs(
id int auto_increment not null,
data datetime not null,
user_id int not null,
name varchar(100) not null,
action varchar(200) not null,
primary key(id)
);

mysql>
mysql> grant insert,select on uwarebot to 'uwarebot'@'localhost';

Crie o arquivo de classe dos logs:

vim class.logs.php

<?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();
     }
  }
}
?>

Crie o arquivo uwarebot.php e modifique <token> e <user id>

<user id> é seu id no Telegram.

Você pode precisar modificar o ip do servidor que recebe as mensagens (log nginx).

<?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);
?>

Adicione a seguinte linha ao arquivo /etc/sudoers:

nginx ALL=NOPASSWD: /bin/fail2ban-client status sshd , /bin/journalctl -u sshd --no-pager -n 20 , /bin/tail /var/log/nginx/error.log , /bin/top , /bin/ls , /bin/ping , /bin/whois

Coloque os dois arquivos dentro do seu servidor https na mesma pasta.

Entre nesta página com as devidas alterações:

https://api.telegram.org/bot<token>/setwebhook?url=https://<URL>/uwarebot.php

O resultado será:

{“ok”:true,”result”:true,”description”:”Webhook was set”}

Fim.

Pronto, seu Simple Server Monitor Bot deve estar rodando. Para inserir mais funções utilize o escopo delas.

Outras dicas deste autor

Tutorial GIT

Verificar CPF/CNPJ em PHP

Instalação do tigervnc com certificado SSL

Abrindo mais de um cliente Telegram

Instalando Placa Nvidia no Fedora Core 27

Leitura recomendada

Arch Wiki Lite

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

Codecs de vídeo para o Totem

  

Comentários
[1] Comentário enviado por rleutz em 16/01/2019 - 17:15h

Atualização e melhorias.....

Github do bot:

https://github.com/rodrigoleutz/uwarebot


------------------------------------------------------------------------
https://www.uware.com.br
Arch

[2] Comentário enviado por edivandjs em 23/03/2019 - 09:37h

Muito interessante

________________
“Quem combate monstruosidades deve cuidar para que não se torne um monstro. E se você olhar longamente para um abismo, o abismo também olha para dentro de você”
Nietzsche.



Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts