监听本机tcp和udp的端口

时间:2023-03-08 16:29:19
#!/bin/bash
#tcp part
port1=`netstat -an|grep LISTEN|egrep "0.0.0.0|:::"|awk '/^tcp/ {print $4}'|awk -F: '{print $2$4}'|sort -n`
echo "TCP state:"
echo "--------------------------------"
echo "PORT PID COMMAND"
for a in $port1
do
b=`lsof -n -i:$a|grep TCP|grep LISTEN|grep IPv4|awk '{printf("%d\t%s\n"),$2,$1}'`
echo "$a $b"
done
echo "--------------------------------" #udp part
echo ""
port2=`netstat -an|grep udp|awk '{print $4}'|awk -F: '{print $2}'|sed '/^$/d'|sort -n`
echo "UDP state:"
echo "--------------------------------"
echo "PORT PID COMMAND"
for a in $port2
do
b=`lsof -n -i:$a|grep UDP|grep IPv4|awk '{printf("%d\t%s\n"),$2,$1}'`
if [ -n "$b" ];then
echo "$a $b"
fi
done
echo "--------------------------------" exit 0