Jee*_*tel 34 linux fedora port command-line
是否有任何命令行命令或任何其他方式来查找和列出我的 Linux 机器上的繁忙和空闲端口号?
Pau*_*aul 46
命令
netstat -antu
Run Code Online (Sandbox Code Playgroud)
将显示所有正在使用的 tcp 和 udp 端口。输出将如下所示:
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:59753 0.0.0.0:* LISTEN
Run Code Online (Sandbox Code Playgroud)
Local Address 字段中冒号后的数字显示正在使用的端口。如果状态为“LISTEN”,则表示用于传入连接的端口。如果该Local Address
字段中的 IP 地址是,0.0.0.0
则意味着将在分配给接口的任何 IP 地址上接受传入连接 - 因此这意味着来自您机器外部的连接。
如果它说localhost
或者127.0.0.1
它只会接受来自您机器的连接。
此外,如果您添加-p
参数,并以 root 身份运行它,它将显示打开端口的进程:
$ sudo netstat -antup
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:59753 0.0.0.0:* LISTEN 860/rpc.statd
Run Code Online (Sandbox Code Playgroud)
任何未显示在使用中的都是免费的,但是用户(非特权帐户)只能打开 1023 以上的端口。
一种检查打开的端口的好而可靠的方法是使用ss
(替换已弃用的 netstat
),它可以在脚本中使用而无需提升权限(即sudo
)。
用法:-l
监听端口选项-n
、绕过 DNS 解析选项和源端口过滤器NN
:(src :NN
替换NN
为您要监控的端口)。有关更多选项,请参阅man ss
ss -ln src :NN
Run Code Online (Sandbox Code Playgroud)
例子:
[user@server ~]# ss -ln src :80
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:80 *:*
[user@server ~]# ss -ln src :81
State Recv-Q Send-Q Local Address:Port Peer Address:Port
Run Code Online (Sandbox Code Playgroud)
在脚本中,使用 grep,我们可以测试输出是否包含我们请求的端口。使用端口 80 的示例(见上文):
myport=80
# count the number of occurrences of port $myport in output: 1= in use; 0 = not in use
result=$(ss -ln src :$myport | grep -Ec -e "\<$myport\>")
if [ "$result" -eq 1 ]; then
echo "Port $myport is in use (result == $result) "
else
echo "Port $myport is NOT in use (result == $result) "
fi
# output:
Port 80 is in use (result == 1)
Run Code Online (Sandbox Code Playgroud)
未使用端口 81 的示例(见上文)
myport=81
result=$(ss -ln src :$myport | grep -Ec -e "\<$myport\>")
if [ "$result" -eq 1 ]; then
echo "Port $myport is in use (result == $result) "
else
echo "Port $myport is NOT in use (result == $result) "
fi
# output:
Port 81 is NOT in use (result == 0)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
188655 次 |
最近记录: |