有一门网络安全课程,其中一项练习是制作端口扫描仪。我认为我的有效,但即时反馈仍然没有给我加分。以下是练习:
import sys
import socket
def get_accessible_ports(address, min_port, max_port):
found_ports = []
# write code here
return found_ports
def main(argv):
address = sys.argv[1]
min_port = int(sys.argv[2])
max_port = int(sys.argv[3])
ports = get_accessible_ports(address, min_port, max_port)
for p in ports:
print(p)
# This makes sure the main function is not called immediatedly
# when TMC imports this module
if __name__ == "__main__":
if len(sys.argv) != 4:
print('usage: python %s address min_port max_port' % sys.argv[0])
else:
main(sys.argv)
对于这个赋值,您应该编写方法get_accessible_ports扫描给定范围的端口所需的代码。该方法应该扫描给定地址的端口,然后返回有服务侦听的端口列表。
请注意,测试服务器不会提交任何数据;你不应该试图接收任何数据。
这是我的代码:
import sys
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def get_accessible_ports(address, min_port, max_port):
found_ports = []
while min_port <= max_port:
try:
s.connect(address, min_port)
except:
min_port += 1
continue
else:
found_ports.append(min_port)
min_port += 1
continue
return found_ports
def main(argv):
address = sys.argv[1]
min_port = int(sys.argv[2])
max_port = int(sys.argv[3])
ports = get_accessible_ports(address, min_port, max_port)
for p in ports:
print(p)
# This makes sure the main function is not called immediatedly
# when TMC imports this module
if __name__ == "__main__":
if len(sys.argv) != 4:
print('usage: python %s address min_port max_port' % sys.argv[0])
else:
main(sys.argv)
以下是练习的反馈:测试:part1-01.portscanner失败:test.test_portscanner.portscanner.testrongcan列表不同:[]!=[25964]
第二个列表包含1个附加元素。第一个额外元素0:25964
- []
- [25964]:端口扫描仪未找到正确的端口
失败:test.test_portscanner.portscanner.testrongingle列表不同:[]!=[224600]
第二个列表包含1个附加元素。第一个额外元素0:24600
- []
- [24600]:端口扫描程序在使用min_port=max_port调用时未测试端口
测试结果:通过了0/2次测试0%[░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░]
知道发生了什么吗??我们将非常感谢您的帮助,谢谢
在没有任何输出的情况下,您将静音所有可能的异常,而不是特定的异常(与连接问题有关(:
try:
...
except:
...
这就是为什么您忽略了address:socket.connect((接受(host, port)
元组的问题。这是一个单个参数,而不是两个。
s.connect(address, min_port)
# ->
s.connect((address, min_port))
除此之外,请尝试在函数内部初始化套接字,不要使用一个套接字来测试所有端口:
def fn(addr, min_port, max_port):
while min_port <= max_port:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.connect((addr, min_port))
except <SOME SPECIFIC EXCEPTION THAT MEANS THE PORT IS UNREACHABLE>:
pass
except Exception:
print('SOMETHING REALLY BAD HAPPENED!')
print('BUT NOW AT LEAST YOU CAN SEE IT HAPPENED:)')
raise
else:
yield min_port
finally:
min_port += 1