例如,我正在尝试编写一个python程序,它将平扫给定的网络(192.168.0.0/24)。然后将存活的主机存储在一个数组中。从该数组中,我希望使用我编写的函数对它们进行端口扫描。然而,我不知道我做错了什么。
下面是一个精简的脚本版本,它不使用活动的主机,只使用整个子网(同样的想法):
#!/usr/bin/env python
import socket
import ipaddress
def portscan(host):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
for port in range(75,85):
result = sock.connect_ex((host, port))
if result == 0: #the error indictator returns 0 if the operation succeeds.
print "port ",port," is open on ", host
# else:
# print "port ",port," is closed"
sock.close()
logging.debug(i)
except:
print "no connection on port",port, "from host",host
def main():
subnet = ipaddress.ip_network(u'192.168.0.0/29')
for i in subnet:
print i
portscan(i)
if __name__ == "__main__":
main() 上面的内容只是返回:
192.168.0.0
no connection on port 75 from host 192.168.0.0
192.168.0.1
no connection on port 75 from host 192.168.0.1
192.168.0.2
no connection on port 75 from host 192.168.0.2
192.168.0.3
no connection on port 75 from host 192.168.0.3
192.168.0.4
no connection on port 75 from host 192.168.0.4
192.168.0.5
no connection on port 75 from host 192.168.0.5
192.168.0.6
no connection on port 75 from host 192.168.0.6
192.168.0.7
no connection on port 75 from host 192.168.0.7
[Finished in 0.0s]我还编写了一个脚本,它在一个特定的主机上运行一个端口扫描,它运行得很好:
#!/usr/bin/env python
import socket
import sys
server = '192.168.0.1'
def portscanner():
try:
for port in range(1,445):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((server, port))
if result == 0: #the error indictator returns 0 if the operation succeeds.
print "port",port," is open on",server
# else:
# print "port ",port," is closed"
sock.close()
except KeyboardInterrupt:
print " CTRL+C Interruption. Exiting..."
sys.exit()
portscanner()硬编码ip返回:
port 80 is open on 192.168.0.1
port 443 is open on 192.168.0.1
[Finished in 20.3s]我已经写了这么多不同的变体来使它发挥作用。但我一直搞错了!我也是Python的新手,所以温柔点!
TL;DR:迭代一组IP地址,并在每个IP地址上调用端口扫描函数。
发布于 2018-04-16 20:53:59
try:
for port in range(75,85): for循环位于try块内--一旦连接尝试的一个失败,它就直接跳到except子句,并跳过循环中的所有其他端口。由于大多数系统不会打开端口75,这将导致“扫描”失败。
将for循环移到try之外,就像在其他脚本中一样。
https://stackoverflow.com/questions/49865999
复制相似问题