Tell us what’s happening:
My code seems to be working well, and all the expected outputs in the tests are exactly equal to mine, so everything should work fine. The problem is that the last 3 tests are still failing, even when I print my output it looks exactly the same as the expected from the asserts.
Your code so far
import socket
import re
from common_ports import ports_and_services
def get_open_ports(target, port_range, verbose=False):
ip = ""
open_ports = []
try:
ip = socket.gethostbyname(target)
for port in range(port_range[0], port_range[1] + 1):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
result = s.connect_ex((ip, port))
if result == 0:
open_ports.append(port)
s.close()
except KeyboardInterrupt:
return "Exiting program!!!"
except socket.gaierror:
if re.search('[a-zA-Z]', target):
return "Error: Invalid hostname"
return "Error: Invalid IP address"
except socket.error:
return "Error: Invalid IP address"
host = None
try:
host = socket.gethostbyaddr(ip)[0]
except socket.herror:
host = None
final_string = f"Open ports for {host or target} ({ip})\n"
if verbose:
header = "PORT SERVICE\n"
body = ""
for port in open_ports:
service_name = ports_and_services.get(port, "unknown")
body += f"{port}{' ' * (9 - len(str(port)))}{service_name}\n"
print(final_string + header + body)
return final_string + header + body
return open_ports
These are the outputs I am getting from printing my results:
***Tests***
.....Open ports for scanme.nmap.org (45.33.32.156)
PORT SERVICE
22 ssh
80 http
FOpen ports for hackthissite.org (137.74.187.104)
PORT SERVICE
443 https
FOpen ports for 104.26.10.78 (104.26.10.78)
PORT SERVICE
443 https
F
Assertion errors all look like this:
======================================================================
FAIL: test_port_scanner_verbose_hostname_multiple_ports (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/runner/boilerplate-port-scanner/test_module.py", line 40, in test_port_scanner_verbose_hostname_multiple_ports
self.assertEqual(actual, expected, "Expected 'Open ports for scanme.nmap.org (45.33.32.156)\nPORT SERVICE\n22 ssh\n80 http'")
AssertionError: 'Open[28 chars]45.33.32.156)\nPORT SERVICE\n22 ssh\n80 http\n' != 'Open[28 chars]45.33.32.156)\nPORT SERVICE\n22 ssh\n80 http'
Open ports for scanme.nmap.org (45.33.32.156)
PORT SERVICE
22 ssh
- 80 http
? -
+ 80 http : Expected 'Open ports for scanme.nmap.org (45.33.32.156)
PORT SERVICE
22 ssh
80 http'
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36
Challenge: Information Security Projects - Port Scanner
Link to the challenge: