我创建了一个基本的 Python 端口扫描器,它允许我扫描 IP 地址或主机名,并可以指定特定端口或定义要扫描的端口范围。我的代码如下:
# import modules used in port scanner
import optparse
from socket import *
from threading import *
# connect-scan function, deals with connecting to the host / determining if
ports are open / closed, takes arguments tgtHost, tgtPort
def connScan(tgtHost, tgtPort):
try:
connSkt = socket(AF_INET, SOCK_STREAM)
connSkt.connect((tgtHost, tgtPort))
connSkt.send('\r\n')
result = connSkt.recv(100)
# prints result if port is open
print '[+] ' + str(tgtPort) + '/tcp open'
except:
# prints result if port is closed
print '[-] ' + str(tgtPort) + '/tcp closed'
finally:
connSkt.close()
# port-scan function, takes arguments tgtHost, tgtPorts
def portScan(tgtHost, tgtPorts):
try:
# tries to get target IP address
tgtIP = gethostbyname(tgtHost)
except:
# if unsuccesful, prints out following result
print '[-] cannot resolve ' + tgtHost + ': unknown host'
return
try:
# tries to get target address
tgtName = gethostbyaddr(tgtIP)
print '\n[+] scan results for: ' + tgtName[0]
except:
print '\n[+] scan results for: ' + tgtIP
# sets default time out to 1
setdefaulttimeout(1)
# for every port in tgtPorts
for tgtPort in tgtPorts:
# creates thread, target is connScan function, arguments are tgtHost, int(tgtPort)
t = Thread(target=connScan, args=(tgtHost, int(tgtPort)))
# starts the thread
t.start()
def main():
parser = optparse.OptionParser('usage %prog -t <target-host> -p <target-port(s)>')
parser.add_option('-t', dest='tgtHost', type='string', help='specify target host')
parser.add_option('-p', dest='tgtPort', type='string', help='specify target port(s), seperated by a comma, seperate ranges with a -')
(options, args) = parser.parse_args()
if (options.tgtHost == None) | (options.tgtPort == None):
print parser.usage
exit(0)
else:
tgtHost = options.tgtHost
# allows ranges of ports to be used, when seperated by a -
if '-' in str(options.tgtPort):
tgtPorts = options.tgtPort.split('-')
tgtPorts = range(int(tgtPorts[0]),int(tgtPorts[1]))
else:
tgtPorts = str(options.tgtPort).split(',')
portScan(tgtHost, tgtPorts)
if __name__ == '__main__':
main()
我知道所有这些代码是如何工作的,但我需要实现一个允许我扫描 IP 地址的本地子网的功能,所以如果我以 (python portscanner.py -t 192.168.1.0 -p 1 -50) 它将扫描本地子网中的所有 IP,即 192.168.1.1 - 192.168.1.255。
不知道怎么实现这个功能,网上找了没用。任何帮助将不胜感激。
请您参考如下方法:
built-in ipaddress module可以帮你解决这个问题。链接的文档页面包括以下示例:
>>> net4 = ipaddress.ip_network('192.0.2.0/24')
>>> for x in net4.hosts():
... print(x)
192.0.2.1
192.0.2.2
192.0.2.3
192.0.2.4
...
192.0.2.252
192.0.2.253
192.0.2.254
我强烈建议您考虑使用 CIDR Notation对于如图所示的 IP 地址范围,因为库可以直接处理这些表示。
从评论看来,您需要一个 IP 地址,其最后一个字节为零才能被视为 /24 子网我建议在您的 main 功能:
tgtHost = options.tgtHost
if tgtHost.endswith('.0'):
hosts = ipaddress.ip_network(tgtHost+'/24')
else:
hosts = [tgtHost]
...
# port handling stuff
...
for tgtHost in hosts:
portScan(tgtHost, tgtPorts)
