Created
December 18, 2025 17:56
-
-
Save AgustinParmisano/4d810bc8318439ea4ebc81617c001d7c to your computer and use it in GitHub Desktop.
Script that gets services and ports from unix systems using only bash commands
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # Verificar privilegios de root | |
| if [ "$EUID" -ne 0 ]; then | |
| echo "Error: Este script debe ejecutarse con sudo." | |
| exit 1 | |
| fi | |
| FORMAT=${1:-json} | |
| # Generar datos base usando ss y filtrando solo servicios con PID | |
| # Se eliminó -H para asegurar que detectamos las columnas correctamente | |
| RAW_DATA=$(ss -tulpn | grep "LISTEN" | grep "users:") | |
| if [ "$FORMAT" == "csv" ]; then | |
| echo "Puerto,Protocolo,Servicio,PID,Version,Ruta_Binario" | |
| fi | |
| if [ "$FORMAT" == "json" ]; then echo "["; fi | |
| FIRST=true | |
| while read -r line; do | |
| # Extraer Protocolo (tcp/udp) | |
| PROTO=$(echo "$line" | awk '{print $1}') | |
| # Extraer Puerto (maneja formatos IPv4 e IPv6) | |
| PORT=$(echo "$line" | awk '{print $5}' | rev | cut -d: -f1 | rev) | |
| # Extraer PID y Nombre del proceso de la cadena "users:(("name",pid=123,fd=4))" | |
| PID=$(echo "$line" | grep -oP 'pid=\K[0-9]+' | head -1) | |
| NAME=$(echo "$line" | grep -oP '(?<=")[^"]+(?=")' | head -1) | |
| if [ -n "$PID" ]; then | |
| # Ruta absoluta del binario desde /proc | |
| BINARY_PATH=$(readlink -f /proc/"$PID"/exe 2>/dev/null || echo "N/A") | |
| # Obtener versión del servicio | |
| VERSION=$($BINARY_PATH -v 2>&1 | head -n 1 | tr -d '",' | xargs || \ | |
| $BINARY_PATH --version 2>&1 | head -n 1 | tr -d '",' | xargs || \ | |
| echo "N/A") | |
| if [ "$FORMAT" == "csv" ]; then | |
| echo "$PORT,$PROTO,$NAME,$PID,\"$VERSION\",$BINARY_PATH" | |
| else | |
| if [ "$FIRST" = true ]; then FIRST=false; else echo ","; fi | |
| cat <<EOF | |
| { | |
| "puerto": "$PORT", | |
| "protocolo": "$PROTO", | |
| "servicio": "$NAME", | |
| "pid": $PID, | |
| "version": "$VERSION", | |
| "path": "$BINARY_PATH" | |
| } | |
| EOF | |
| fi | |
| fi | |
| done <<< "$RAW_DATA" | |
| if [ "$FORMAT" == "json" ]; then echo -e "\n]"; fi |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$ sudo osqueryi --json "
SELECT
lp.port,
lp.protocol,
p.name AS servicio,
p.pid,
p.path AS binario_path,
COALESCE(pkg.version, 'No detectada') AS version
FROM listening_ports AS lp
JOIN processes AS p ON lp.pid = p.pid
LEFT JOIN deb_packages AS pkg ON p.name = pkg.name
WHERE p.name IN ('apache2', 'nginx', 'mysqld', 'postgres', 'redis-server', 'mongod', 'node', 'memcached', 'influxd')
OR p.cmdline LIKE '%httpd%'
OR p.cmdline LIKE '%server%'
OR p.cmdline LIKE '%database%';
"