#!/bin/sh
#	servers 0.03
#	Active servers in this moment	Servicios activos en este momento
#
#	Copyright (C) 2001:	Manel Marin <manel3@wanadoo.es>
#	Licence:		GNU GPL version >= 2
#
#	Use:   servers			Uso:   servers
#	Debug: servers -d		Debug: servers -d
#
#
# 0.02  8.7.01
# 0.03 22.7.01 +inetd/portmap to HINT


exec 2>&1	# Enviar errores a stdout ( Gracias a Luis Colorado ;)


# GESTIONA MODO DEBUG
if [ "$1" = "-d" ]
then
    shift		# Salto parametro / Skip parameter
    DEBUG="-d"		# Activo debug / debug active
fi


# MENSAJE Y CABECERA

echo
echo "ACTIVE SERVERS IN THIS MOMENT"
echo "(netstat -tuna  +  fuser -v port/proto)"
echo
echo "Proto Port  Service      Process              Local IP        User"
echo "-------------------------------------------------------------------------"


# BUCLE PRINCIPAL

netstat -an | awk -v debug="$DEBUG" '

  {
	if( debug ) print "---------------------------------------------------"
	if( debug ) print $0
  }

    # SOLO PROCESAR LAS LINEAS CON PUERTOS ABIERTOS (SALTAR LAS DEMAS)
  $0 !~ "0.0.0.0:" { next }

  {
	    # CAMPOS DE NETSTAT
	    # $1=proto $2=recvQ $3=sendQ $4=local $5=remote $6=state
	proto = $1
	local = $4

	    # SEPARO PORT E IP DE LOCAL
	split( local, part, ":")			# Separo en "part"
	ip = part[1]
	port = part[2]

	    # BUSCO NOMBRE DE SERVICIO EN /etc/services
	service = ""					# inicializo a ""
	while( 1 == getline < "/etc/services" )
	{
    	    if( $2 == port"/"proto ){ service = $1 }
	}
	close( "/etc/services" )			# reset de getline

	    # BUSCO PROCESO CON fuser
	if( proto == "raw" ) process = "-"
	else{
	    lines = 0
	    command = "fuser -v " port "/" proto
	    while( 1 == command | getline )
	    {
		if( debug ) print $0
		if( $1 ~ "/")
		{
		    process = $5		# Tomar solo primera linea
		    user = $2
		    pid = $3
		}
		lines = lines + 1
	    }
	    close ( command )				# cierro el pipe


		# SI FALLA "fuser" (USUARIO NO ES ROOT) PONGO ?
	    if( process == "" ){
		process = "?"
		user = "?"
		if( onlyroot == "" ){
		    print "Only root can find process and user...\n"
		    onlyroot = "said"
		}
	    }
	    else{
		lines = lines - 2		# Dos lineas de cabecera
		if( lines > 1 ) process = process " x " lines
	    }
	}

	    # SUSTITUYO IPs
	if( ip == "0.0.0.0" ) ip = "*"
	if( ip == "127.0.0.1" ) ip = "(lo)"

	    # PONGO LINEA
	if( debug ) print ""
	printf( "%-4s %5s  %-12s %-20s %-15s %-8s\n", \
	  proto, port, service, process, ip, user )
	    
  }' # FIN

echo
echo "HINT: In Debian"
echo "find path:        which process"
echo "find package:     dpkg --search process-with-path"
echo "uninstall it:     apt-get remove package   *OR*   dpkg --remove package"
echo "inetd/portmap:    update-rc.d -f inetd remove   #netbase not removable"
echo "                  /etc/init.d/inetd stop        #and no reboot needed"
echo
exit
