端口扫描 python 中的 IP 范围

port scanning an IP range in python

所以我正在 python 中为 class 开发一个简单的端口扫描器(不允许使用 python-nmap 库),虽然我可以得到它要在传递单个 IP 地址时工作,我无法使用一系列 IP 使其工作。

这是我的:

#!/usr/bin/env python
from socket import *
from netaddr import *

# port scanner
def port_scan(port, host)
   s = socket(AF_INET, SOCK_STREAM)
   try:
      s = s.connect((host, port))
      print "Port ", port, " is open"
   except Exception, e:
      pass

# get user input for range in form xxx.xxx.xxx.xxx-xxx.xxx.xxx.xxx and xx-xx
ipStart, ipEnd = raw_input ("Enter IP-IP: ").split("-")
portStart, portEnd = raw_input ("Enter port-port: ").split("-")

# cast port string to int
portStart, portEnd = [int(portStart), int(portEnd)]

# define IP range
iprange = IPRange(ipStart, ipEnd)

# this is where my problem is
for ip in iprange:
   host = ip
   for port in range(startPort, endPort + 1)
      port_scan(port, host)

所以当我运行代码时,在下面添加打印语句后

host = ip
print host   # added

然后在

之后再次
port_scan(port, host)
print port   # added

我最终得到以下输出:

root@kali:~/Desktop/python# python what.py
Enter IP-IP: 172.16.250.100-172.16.250.104
Enter port-port: 20-22
172.16.250.100
20
21
22
172.16.250.101
20
21
22
...and so on

提前谢谢大家! 我很感激能得到的任何帮助!

code picture for reference, slightly different

output picture for reference

问题原来是使用 netaddr.IPRange 的问题,正如@bravosierra99 所建议的那样。

再次感谢大家!