Python编程–目标IP地址段主机指定端口状态扫描
渗透测试经常需要进行针对目标主机IP地址段的各主机的端口进行扫描,然后输出目标主机的开放端口的状态。现利用nmap-python模块编写一个扫描脚本程序。代码如下:
# 导入nmap模块
import nmap
# 定义findTgts函数,参数为subNet(目标子网), portLst(目标端口列表)
def findTgts(subNet, portLst):
# 实例化nmap对象
nmScan = nmap.PortScanner()
# 遍历目标端口
for port in portLst:
nmScan.scan(subNet, str(port))
# 建立一个目标主机空列表
tgtHosts = []
for host in nmScan.all_hosts():
if nmScan[host].has_tcp(port):
# 获取目标主机tcp协议的目标端口的状态
state = nmScan[host]['tcp'][port]['state']
# 判断端口状态是否开放
if state == 'open':
print('[+] Found Target Host: ' + host + ' ' + 'port: ' + str(port) + ' open')
tgtHosts.append(host)
return tgtHosts
if __name__ == '__main__':
portLst = [21, 22, 25, 445]
tgthosts = findTgts('192.168.31.33-240', portLst)
print(tgthosts)
针对目标IP地址段(192.168.31.33-240)端口(21,22, 25, 445)进行扫描,结果如下所示:
[+] Found Target Host: 192.168.31.82 port: 21 open
[+] Found Target Host: 192.168.31.82 port: 22 open
[+] Found Target Host: 192.168.31.113 port: 445 open
[+] Found Target Host: 192.168.31.192 port: 445 open
['192.168.31.82', '192.168.31.113', '192.168.31.192']