怎样在linux或者Unix上检查端口是否在使用

时间:2021-01-17 07:44:07

 英文原文链接:https://www.cyberciti.biz/faq/unix-linux-check-if-port-is-in-use-command/

Question 1: 怎样在linux或者类Unix系统上确定端口(port)是否在使用中?

Question 2: 怎么在linux服务器上验证某个端口(port)正在监听中?

  确定那个端口正在监听服务器的网络接口是很重要的。你需要花费精力打开端口检查是否被入侵(intrusion)。除了端口入侵外,即使出于解决问题的目的,检查某个端口是否被你服务器上的另一个app使用可能也是必要的。例如你在统一太服务器上安装完Appache和Nginx后,知道Appache和Naginx是否正在使用TCP端口80/443是很有必有的。接下来的快速指南将通过分别用netstat、nmap和lsof指令去检查端口是否正在被使用,然后查某个Appp是否正在使用这个端口。

step1、打开终端

step2、运行任一指令
    sudo lsof -i -P -n | grep LISTEN
    sudo netstat -tulpn | grep LISTEN
    sudo nmap -sTU -O IP-address-Here

<1> lsof

[root@localhost ~]# lsof -i -P -n | grep LISTEN
sshd root 3u IPv4 0t0 TCP *: (LISTEN)
sshd root 4u IPv6 0t0 TCP *: (LISTEN)
dnsmasq nobody 7u IPv4 0t0 TCP 192.168.122.1: (LISTEN)
dnsmasq nobody 12u IPv6 0t0 TCP [fe80:::ff:fef2:4af0]: (LISTEN)
dnsmasq nobody 7u IPv4 0t0 TCP 192.168.123.1: (LISTEN)
cupsd root 10u IPv6 0t0 TCP [::]: (LISTEN)
cupsd root 11u IPv4 0t0 TCP 127.0.0.1: (LISTEN)
smbd root 31u IPv6 0t0 TCP *: (LISTEN)
smbd root 32u IPv6 0t0 TCP *: (LISTEN)
smbd root 33u IPv4 0t0 TCP *: (LISTEN)
smbd root 34u IPv4 0t0 TCP *: (LISTEN)

说明:

  • dnsmasq 应用程序名字.
  • 192.168.123.1  dnsmasq 监听端口绑定的IP地址
  • 53  监听的端口号
  • 718  dnsmasq进程号

<2> netstat

[root@localhost ~]# netstat -tulpn | grep LISTEN
tcp 0.0.0.0: 0.0.0.0:* LISTEN /smbd
tcp 0.0.0.0: 0.0.0.0:* LISTEN /smbd
tcp 192.168.123.1: 0.0.0.0:* LISTEN /dnsmasq
tcp 192.168.122.1: 0.0.0.0:* LISTEN /dnsmasq
tcp 0.0.0.0: 0.0.0.0:* LISTEN /sshd
tcp 127.0.0.1: 0.0.0.0:* LISTEN /cupsd
tcp6 ::: :::* LISTEN /smbd
tcp6 ::: :::* LISTEN /smbd
tcp6 fe80:::ff:fef2:: :::* LISTEN /dnsmasq
tcp6 ::: :::* LISTEN /sshd
tcp6 ::: :::* LISTEN /cupsd

<3> nmap 使用方法:

$ sudo nmap -sT -O localhost
$ sudo nmap -sU -O 192.168.2.13 ##[ list open UDP ports ]##
$ sudo nmap -sT -O 192.168.2.13 ##[ list open TCP ports ]##

[root@localhost ~]# nmap -sT -O localhost

Starting Nmap 6.47 ( http://nmap.org ) at 2017-01-12 13:21 CST
Nmap scan report for localhost (127.0.0.1)
Host is up (.000048s latency).
rDNS record for 127.0.0.1: localhost.localdomain
Not shown: closed ports
PORT STATE SERVICE
/tcp open ssh
/tcp open netbios-ssn
/tcp open microsoft-ds
/tcp open ipp
Device type: general purpose
Running: Linux .X
OS CPE: cpe:/o:linux:linux_kernel:
OS details: Linux 3.7 - 3.15
Network Distance: hops OS detection performed. Please report any incorrect results at http://nmap.org/submit/ .
Nmap done: IP address ( host up) scanned in 1.53 seconds

You can combine TCP/UDP scan in a single command:

同时也可在一条指令中添加TCP/UDP扫描
    $ sudo nmap -sTU -O 192.168.2.13

windows 用户建议:
     netstat -bano | more
    netstat -bano | grep LISTENING
    netstat -bano | findstr /R /C:"[LISTEING]"