【问题标题】:Get details of all tcp listening processes获取所有 tcp 监听进程的详细信息
【发布时间】:2015-07-20 01:21:30
【问题描述】:
#! /bin/bash

a=`netstat -plant | grep -i listen`

#to get ip and port
b=`echo $a | awk {'print $4}'`

#to get the process id
c=`echo $a | awk {'print $7}' | awk -F '/' {'print $1'}`
set -- $c

#to get the details of process
g=`ps aux | grep $1`

m=`echo $g | awk {'print $2}'`
n=`echo $g | awk {'print $9}'`
o=`echo $g | awk {'print $11}'`


echo The process with PID $m invoked by command "$o", is listening at IP and Port : $b . The process has been running since $n

我试图制作一个脚本来以一种简单的语言显示 PID、IP、端口、运行以来的详细信息以及所有 tcp 侦听进程的命令。我制作的脚本只给出了 1 个进程的详细信息

【问题讨论】:

  • 使用括号比使用旧的反引号更好,例如:m=$(echo $g | awk {'print $2}'。双引号变量也很好,所以:m=$(echo "$g" | awk {'print $2}' 或像这样:m=$(awk {'print $2}' <<< "$g"

标签: shell awk sed scripting grep


【解决方案1】:

您只需使用while read 构造将分配更改为a

netstat -plant | grep -i listen | while read a; do

    #to get ip and port
    b=`echo $a | awk {'print $4}'`

    #to get the process id
    c=`echo $a | awk {'print $7}' | awk -F '/' {'print $1'}`
    set -- $c

    #to get the details of process
    g=`ps aux | grep $1`

    m=`echo $g | awk {'print $2}'`
    n=`echo $g | awk {'print $9}'`
    o=`echo $g | awk {'print $11}'`

    echo The process with PID $m invoked by command "$o", is listening at IP and Port : $b . The process has been running since $n

done

这个结构会一次一行地将 grep 的输出读取到 a 变量中。

【讨论】:

  • 使用括号比使用旧的反引号更好,例如:m=$(echo "$g" | awk {'print $2}'
  • @Jotne 真的。很多事情需要“修复”:为什么要使用set --,awk 的奇怪引用位置,awk 的重复使用太多。
  • 有更简单的方法吗?我是脚本新手,用有限的资源制作了这个脚本。
  • 不使用 grep,您可以使用 -p 选项直接将 PID 指定给 ps 命令。也可以使用-o 选项指定字段。例如:ps -h -p $c -o pid,start_time,cmd 将仅显示 pid=$c 的 3 个字段。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-16
相关资源
最近更新 更多