centos7脚本查看打印所有端口

2024-01-02 22:32:30

查看端口命令

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

? ? ? ? ]
}
?

文章来源:https://blog.csdn.net/qq_24768591/article/details/135350527
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。