bash 删除 netstat 输出(特别是不能识别所有进程的行)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32611891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:34:37  来源:igfitidea点击:

Remove netstat output (specifically Not all processes could be identified line)

bashshellunixio-redirectionnetstat

提问by Zee

I'm having trouble removing the output from the netstat command when I check if a current port is being used. I dont need the output of the command but rather just the error code.

当我检查是否正在使用当前端口时,我无法从 netstat 命令中删除输出。我不需要命令的输出,而只需要错误代码。

Running netstat -anp | grep 1521 &>/dev/nullresults in

运行netstat -anp | grep 1521 &>/dev/null结果

(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)

being shown as the output. I have also tried:

显示为输出。我也试过:

2>/dev/null| cut -d' ' -f45-50 | sed 's/[^0-9]*//g'

which just results in a bunch of empty lines after the Not all processes... output but still displays that in the output.

这只会在 Not all processes... 输出之后产生一堆空行,但仍然在输出中显示。

回答by Zee

ended up solving my own problem. Use the following

最终解决了我自己的问题。使用以下

netstat -taepn 2>/dev/null | grep -Po "\b(\d|\.)+:1521\b" 1>/dev/null

This is specific for my situation when I just want the error code and no output

当我只想要错误代码而没有输出时,这特定于我的情况

回答by CodyChan

The accepted answer doesn't work for me, CentOS6.5 32bit here. It outputs nothing no matter what state the port is.

接受的答案对我不起作用,这里是 CentOS6.5 32bit。无论端口处于何种状态,它都不输出任何内容。

I found my solution:

我找到了我的解决方案:

netstat -antp 2>/dev/null | grep [port-num]

This will omit the first two lines of netstatif it is executed by regular user.

netstat如果它由普通用户执行,这将省略前两行。

The warning two lines needed to be omitted:

警告两行需要省略:

(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)

and works for two situations:

并适用于两种情况:

  1. the port is "LISTEN" state
  2. the port is "TIME_WAIT" state.
  1. 端口处于“侦听”状态
  2. 端口处于“TIME_WAIT”状态。