本文介绍在Linux下查看端口的几种方法,同时利用Python完成端口扫描来判断端口是否打开。
一、查看端口以及测试是否打开
1、可以查看文件/etc/services,从里面可以找出端口所对应的服务,但是无法判断端口是否打开。

2、telnet可以判断端口是否打开,telnet没有参数控制超时时间。

3、nc(netcat)网络工具来完成端口扫描。

4、可以通过netstat 结合grep 来查看哪些端口被打开。 netstat -ntpl查看TCP类型的端口,netstat -nupl(UDP类型的端口) 。

5、使用nmap 专业工具的强大功能来检测。
下面介绍几个nmap使用方法。
5.1打印扫描的ip列表。

5.2从文件中读取IP地址完成端口扫描。

5.3端口扫描特定的单机的1000个最常用的端口。

5.4端口扫描本机的1000个最常用的端口并显示主机信息。

5.5端口扫描特定的单机的1000个最常用的端口并显示版本信息。

5.6不进行端口扫描,仅仅判断主机是否可达,类似于ping功能。

二、python的socket模块完成端口扫描
函数conn_scan使用socket套接字编程的方式用来判断端口是否可用。

运行结果:

三、python的telnet模块完成端口扫描
函数conn_scan使用标准库的telnet模块,创建telnet对象并不会建立到远程主机的连接,显示的使用open方法建立连接。

运行结果如下:

对比前面两个例子,telnet模块的open方法可用设置超时时间timeout,执行时间是socket套接字的一半,效率更高。
可用针对集群ips和端口ports,可用使用两个for来迭代完成所有ip的端口扫描。

使用列表推导来迭代完成所有ip的端口扫描。

使用product(from itertools import product)返回多个可迭对象的笛卡尔积完成所有ip的端口扫描。

四、python的namp开源库完成端口扫描
python-namp相对于nmap,主要的改进在于对输出结果的处理,输出结果保存在字典之中。

网友评论