I wrote this (below) Port Scanner/Banner Grabber that provides uncompleted results.
If I run it against metasploitable machine on Virtual Box, it returns all open ports and their banners. All seems okay!
If I run it against an online machine (kenobi from tryhackme) it returns:
[+] Scan results for:10.10.124.162
[+]22/tcp open:SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.7
[+]21/tcp open:220 ProFTPD 1.3.5 Server (ProFTPD Default Installation) [10.10.124.162]
I know the port 80, 111 are open, but I don't understand why my code ignores them and doesn't work properly.
Generally speaking I notice that nmap provides very different result, but my aim is not to invent hot water, simply to understand and write basic programs.
#!/usr/bin/python
from socket import *
from threading import *
print ("Basic Port Scanner and Banner Grabbing\n")
def connScan(tgtHost, tgtPort):
try:
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((tgtHost, tgtPort))
banner = sock.recv(2048)
banner = banner.decode('utf-8')
print ("[+]" + str(tgtPort) +"/tcp open:" + banner )
except:
pass
finally:
sock.close()
def portScan(tgtHost):
"""Run the Port Scan selecting by domain name or IP"""
try:
tgtIP = gethostbyname(tgtHost)
except:
print ("Can't Resolve Target host %s" % tgtHost)
try:
tgtName = gethostbyaddr(tgtIP)
print ("[+] Scan results for: " + tgtName [0])
except:
print ("[+] Scan results for:" + tgtIP)
setdefaulttimeout(2)
for tgtPort in range (1, 65535):
# Thread launch a separate flow of instruction that running separately
t = Thread(target=connScan, args=(tgtHost, int(tgtPort)))
t.start()
def main():
"""ask for input"""
tgtHost = input("Insert the host IP Target: ")
portScan(tgtHost)
if __name__ == '__main__':
main()