Programa em C para monitorar IPs e portas ativas

Publicado por Lauro Salmito Pinheiro 30/07/2009

[ Hits: 9.715 ]

Download monitor




Desenvolvi o PortMonitor para que os administradores de redes e segurança da informação possam gerar um relatório de status dos serviços e ficarem monitorando os serviços de vários servidores.

Distributed under GPLv2
Copyright (c) 2009 Lauro Salmito Pinheiro <laurosalmito@gmail.com>

  



Esconder código-fonte

/*
 *         PortMonitor
 * Monitor dos status das portas dos hosts
 *
 * Distribute under GPLv2
 *
 * Copyright (c) 2009 Lauro Salmito Pinheiro <laurosalmito@gmail.com>
 *
*/

#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <time.h>
#include <gtk/gtk.h>
#include <stdlib.h>

#define BUFFSIZE 32


void displayUI(char *str)

{

   GtkWidget* mainWindow = gtk_window_new(GTK_WINDOW_TOPLEVEL);
        GtkWidget* label,*box1,*button,*box2;

   box1 = gtk_vbox_new (FALSE, 0);
        gtk_container_add (GTK_CONTAINER (mainWindow), box1);
        gtk_widget_show (box1);

   box2 = gtk_hbox_new (TRUE, 10);
   gtk_container_set_border_width (GTK_CONTAINER (box2), 0);

   gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, FALSE, 0);

        label = gtk_label_new (str);


        gtk_box_pack_start (GTK_BOX (box1), label, TRUE, FALSE, 0);
   gtk_widget_show (box2);


   gtk_window_set_default_size(GTK_WINDOW(mainWindow), 300, 200);
   gtk_window_set_title(GTK_WINDOW(mainWindow), " ..:: Port Monitor 1.0 ::..");
   gtk_window_set_position(GTK_WINDOW(mainWindow), GTK_WIN_POS_CENTER_ALWAYS);

   gtk_signal_connect(GTK_OBJECT(mainWindow), "destroy", G_CALLBACK(gtk_main_quit), NULL);

    button = gtk_button_new_with_label (" !    OK   !   ");

   g_signal_connect_swapped (G_OBJECT (button), "clicked", G_CALLBACK (gtk_widget_destroy),  G_OBJECT (mainWindow));


    gtk_box_pack_start (GTK_BOX (box2), button, FALSE, FALSE, 0);

       GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
       gtk_widget_grab_default (button);
       gtk_widget_show (button);



       gtk_widget_show (label);



   gtk_widget_show_all(mainWindow);
}




void Die(char *mess) { perror(mess); exit(1);}

void trim(char *s, const int len)
{
    int end = len - 1;
    int start = 0;
    int i = 0;

    while ((start < len) && (s[start] <= ' '))
    {
        start++;
    }

    while ((start < end) && (s[end] <= ' '))
    {
        end--;
    }

    if (start > end)
    {
        memset(s, '{FONTE}', len);
        return;
    }

    for (i = 0; (i + start) <= end; i++)
    {
        s[i] = s[start + i];
    }
    memset((s + i), '{FONTE}', len - i);
}




int connections(const char *ip,const char *port)
{
      int sock,z,linger_return;
      struct sockaddr_in socket_struture;
   struct linger a;
   a.l_onoff=1;
   a.l_linger=0;

   sleep(1);

   if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
      {
      Die("Err:");
           }
   
        memset(&socket_struture, 0, sizeof(socket_struture));
        socket_struture.sin_family = AF_INET;
        socket_struture.sin_addr.s_addr = inet_addr(ip);
        socket_struture.sin_port = htons(atoi(port));

        if ((z = connect(sock,(struct sockaddr *) &socket_struture,sizeof(socket_struture)) == 0)) {
               //printf("Porta %s Ativa:. - %d -\n",port,z); //Debug
      linger_return = setsockopt(sock, SOL_SOCKET, SO_LINGER,&a, sizeof(a));
      close(sock);
      return 1;
            } else {
                 // printf("Porta %s Desconectada:. - %d -\n",port,z); //De
      linger_return = setsockopt(sock, SOL_SOCKET, SO_LINGER,&a, sizeof(a));
      close(sock);
      return 0;
      }
   
}

 int main(int argc, char *argv[])
 {
   
   FILE* filedest,*logfile;
   register int val;
   typedef char string[50];
   string hosts[50];
   string portas[50];
   int j,i =0;
   gtk_init(&argc, &argv);
   char server[200];

  

  

   if (argc>1)
   {
      if(  (argc > 2 || (strcmp(argv[1],"-log")!=0)) && (argc > 2 || (strcmp(argv[1],"-x")!=0))  )
      {
         printf("Numeros de parametros invalidos. Tente somente um parametro!\n");
         exit(1);
      }

   }
   
   filedest = fopen("dest.conf","r");
        if (filedest==NULL)
   {
      printf("Crie um arquivo no diretorio corrente chamado \"dest.conf\" - com os IPS e portas, separando-os com \":\"\n");
      exit(0);
   }
   

    while (!feof(filedest))
       {
         fscanf(filedest,"%s\t%s",hosts[i],portas[i]);
         i++;
        }

   fclose(filedest);

   for (;;)
    {
           time_t mytime;
           mytime = time(NULL);
           char *time_local;
      time_local = ctime(&mytime);
      trim(time_local,strlen(time_local));

      for (j=0;j<i-1;j++)
      {
   
         
         val = connections(hosts[j],portas[j]);
      
         if (!argv[1])
            {
               if (val==1)
               {
                  printf("[%s] Host.::. %s - Porta -> %s ATIVA -\n",time_local,hosts[j],portas[j]);
   
               } else {
                  printf("[%s] Host.::. %s - Porta -> %s DESCONACTDA -\n",time_local,hosts[j],portas[j]);
   
               }
            } else   {   
   
               if(strcmp(argv[1],"-log")==0)
               {
                  //FILE* logfile;
                  logfile = fopen("monitor.log","a+");
   
                  if (val==1)
                  {
                     fprintf(logfile,"[%s] Host.::. %s - Porta -> %s ATIVA -\n",time_local,hosts[j],portas[j]);
                     } else {
                     fprintf(logfile,"[%s] Host.::. %s - Porta -> %s DESCONACTDA -\n",time_local,hosts[j],portas[j]);
                  }
   
                  fclose(logfile);
               }
   
               if(strcmp(argv[1],"-x")==0)
               {
                  if (val==0)
                  {
                     logfile = fopen("monitor.log","a+");
                     fprintf(logfile,"[%s] Host.::. %s - Porta -> %s DESCONACTDA -\n",time_local,hosts[j],portas[j]);
                     fclose(logfile);                     
                     sprintf(server,"Data/Hora::.%s\nHost::.%s\nPorta::.%s\nStatus::.* INATIVO *\n",time_local,hosts[j],portas[j]);
                     displayUI(server);
                     gtk_main();
                  }
               }
            
         }   
         

      }

      }

return(0);
}

Scripts recomendados

Exemplo Básico de Sockets em C

Simples servidor http com concorrência feito em C

Usando sockets para monitorar servidores

Socket em C/C++ - CLIENT

Exemplo de Cliente e Servidor Usando Socket no Linux!


  

Comentários
[1] Comentário enviado por laurosalmito em 30/07/2009 - 14:03h

Funcionamento:

É necessário que seja criando um arquivo com o nome de "dest.conf" no diretório corrente que irá ter os
ips e portas destinos para que seja feita a monitorização.

Exemplo do arquivo "dest.conf"

-8<-------------------

192.168.0.160 22
192.168.0.1 80
192.168.0.3 5000

---------------->8---


Parâmetros do PortMonitor:

monitor [OPÇÕES]

* Quando não é passado nenhum parâmetro ele exibe o status no console.

-x
Grava no arquivo "monitor.log" quando há alguma porta ou IP inativo além de exibir uma tela gráfica no ambiente X11.

-log
Grava no arquivo "monitor.log" todos os staus dos IP's e portas.


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts