如何在Linux中找到服务的端口号

时间:2020-03-21 11:44:28  来源:igfitidea点击:

由于某种原因,我们可能经常需要找到端口名称和数字。

在这篇教程中,我们将看到最简单和最快的方法可以找到Linux操作系统中服务的端口号。

查找Linux中服务的端口号

方法1使用grep命令:

要使用Grep命令查找Linux中给定服务的默认端口号,只需运行:

$grep <port> /etc/services

例如,要查找SSH服务的默认端口,只需运行:

$grep ssh /etc/services

这很简单。
此命令应适用于大多数Linux发行版。
以下是我Arch Linux测试盒的示例输出:

ssh 22/tcp
ssh 22/udp
ssh 22/sctp
sshell 614/tcp
sshell 614/udp
netconf-ssh 830/tcp
netconf-ssh 830/udp
sdo-ssh 3897/tcp
sdo-ssh 3897/udp
netconf-ch-ssh 4334/tcp
snmpssh 5161/tcp
snmpssh-trap 5162/tcp
tl1-ssh 6252/tcp
tl1-ssh 6252/udp
ssh-mgmt 17235/tcp
ssh-mgmt 17235/udp

正如我们在上面的输出中看到的,SSH服务的默认端口号为22.

让我们找到Apache Web服务器的端口号。
为此,命令将是:

$grep http /etc/services
# http://www.iana.org/assignments/port-numbers
http 80/tcp www www-http # WorldWideWeb HTTP
http 80/udp www www-http # HyperText Transfer Protocol
http 80/sctp # HyperText Transfer Protocol
https 443/tcp # http protocol over TLS/SSL
https 443/udp # http protocol over TLS/SSL
https 443/sctp # http protocol over TLS/SSL
gss-http 488/tcp
gss-http 488/udp
webcache 8080/tcp http-alt # WWW caching service
webcache 8080/udp http-alt # WWW caching service
[...]

FTP端口号码怎么样?
这很容易!

$grep ftp /etc/services
ftp-data 20/tcp
ftp-data 20/udp
# 21 is registered to ftp, but also used by fsp
ftp 21/tcp
ftp 21/udp fsp fspd
tftp 69/tcp
[...]

方法2使用Getent命令

如我们所见,上述命令显示给定的搜索词"SSH","HTTP"和"FTP"的所有端口名称和数字。
这意味着,我们将获得与给定搜索项匹配的所有端口名称的相当长的输出。

但是,我们可以使用如下所示的"getent"命令缩小结果缩小结果以确切的输出:

$getent services ssh
ssh 22/tcp
$getent services http
http 80/tcp www www-http
$getent services ftp
ftp 21/tcp

如果我们不知道端口名称但端口号,只需替换以下数字的端口名称,如下所示:

$getent services 80
http 80/tcp

要显示所有端口名称和数字,只需运行:

$getent services

建议阅读:

  • 如何将Apache默认端口更改为自定义端口
  • 如何将FTP默认端口更改为自定义端口
  • 如何将SSH默认端口更改为自定义端口

方法3使用Whatportis实用程序

WhatPortis是一个用于查找端口名称和数字的简单Python脚本。
与上述命令不同,此实用程序以良好的表格列格式显示输出。

确保已安装PIP包管理器。

一旦安装了PIP,请运行以下命令以安装Whatportis实用程序。

$pip install whatportis

现在,我们可以找到与服务相关联的端口,如下所示。

$whatportis ssh
$whatportis ftp
$whatportis http

如果我们不知道服务的确切名称,请使用 -like标志显示相关结果。

$whatportis mysql --like

上面的命令找到了与服务相关联的端口。
我们还可以找到与下面这样的端口号相关联的服务。

$whatportis 993

我们甚至可以以JSON格式显示结果。

$whatportis 993 --json