查看端口命令
netstat -tnlp | egrep -i "$1" | awk '{print $4}' | awk -F':' '{if ($NF~/^[0-9]+$/) print $NF}' | sort | uniq
22
25
脚本
#!/bin/bash
PORT_ARRAY=(`netstat -tnlp | egrep -i "$1" | awk '{print $4}' | awk -F':' '{print $NF}' | sort | uniq`)
length=${#PORT_ARRAY[@]}
printf "{\n"
printf '\t'"\"data\":["
for ((i=0;i<$length;i++))
do
printf '\n\t\t{'
printf "\"%s\": \"%s\"\n" "{#TCP_PORT}" "${PORT_ARRAY[$i]}"
if [ $i -lt $length-1 ];then
printf ','
fi
done
printf "\n\t]\n"
printf "}\n"
输出结果
bash p.sh
{
? ? ? ? "data":[
? ? ? ? ? ? ? ? {"{#TCP_PORT}": "22"
p.sh: line 10: [: 4-1: integer expression expected
? ? ? ? ? ? ? ? {"{#TCP_PORT}": "25"
p.sh: line 10: [: 4-1: integer expression expected
? ? ? ? ? ? ? ? {"{#TCP_PORT}": "Local"
p.sh: line 10: [: 4-1: integer expression expected
? ? ? ? ? ? ? ? {"{#TCP_PORT}": "(only"
p.sh: line 10: [: 4-1: integer expression expected
? ? ? ? ]
}
?
修改后不显示local
#!/bin/bash
PORT_ARRAY=(`netstat -tnlp | egrep -i ":$1" | awk '{print $4}' | awk -F':' '{print $NF}' | sort | uniq`)
length=${#PORT_ARRAY[@]}
printf "{\n"
printf '\t'"\"data\":["
for ((i=0;i<$length;i++))
do
printf '\n\t\t{'
printf "\"%s\": \"%s\"\n" "{#TCP_PORT}" "${PORT_ARRAY[$i]}"
if [ $i -lt $length-1 ];then
printf ','
fi
done
printf "\n\t]\n"
printf "}\n"
bash port.sh
{
? ? ? ? "data":[
? ? ? ? ? ? ? ? {"{#TCP_PORT}": "22"
port.sh: line 10: [: 2-1: integer expression expected
? ? ? ? ? ? ? ? {"{#TCP_PORT}": "25"
port.sh: line 10: [: 2-1: integer expression expected
? ? ? ? ]
}
?