shell脚本获取本机端口号
#netstat -tln
-----输出如下-------
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:5801 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:427 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:5901 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:2544 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:631 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN
tcp 0 0 :::22 :::* LISTEN
tcp 0 0 ::1:25 :::* LISTEN
-------------------------
想得到的输出结果如下:
5801,427,5901,111,2544,631,25,22
请问shell语句要怎么写?
[nicenight@CSDN ~]# netstat -tln | awk 'BEGIN{ORS=","}; NR>2{sub(".*:", "", $4); print $4}'
不过没有过滤重复端口。
会输出两个25
5801,427,5901,111,2544,631,25,22,25
命令:
#netstat -tln | awk '{if($1=="tcp"){num=split($4,A,":");B[A[num]]++;if(B[A[num]]==1)str=str""A[num]","}}END{print substr(str,1,length(str)-1)}'
#cat test.txt
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:5801 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:427 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:5901 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:2544 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:631 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN
tcp 0 0 :::22 :::* LISTEN
tcp 0 0 ::1:25 :::* LISTEN
-------------------------
#awk '{if($1=="tcp"){num=split($4,A,":");B[A[num]]++;if(B[A[num]]==1)str=str""A[num]","}}END{print substr(str,1,length(str)-1)}' test.txt
5801,427,5901,111,2544,631,25,22