I’m following along with the book “Violent Python, a Cookbook for hackers, forensic analysts, pentesters, and security engineers”. It has several tutorials but the code is a little older so a lot of it you kind of need to modify/figure out on your own. Anyways I’m trying to follow along with the tutorial where it teaches you to build your own port scanner using the sockets API. For some reason its not working though. it resolves the hostname fine and I don’t get any errors but everytime it says the port is closed, no matter what ports I enter. Seems like its not making a connection. I’ve searched through the documentation for sockets but cant figure out why it might not be connecting with the target host and port. Any help is much appreciated
## port_scanner.py ##########################################
# import BSD socket
import socket
def connScan(tgtHost, tgtPort):
try:
connSkt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# try to connect to the tgtHost and tgtPort
connSkt.connect((tgtHost, tgtPort))
# send the target some junk data and and print the response we get (banner grabbing)
connSkt.send('rTheseTheDroidsImLooking4\r\n')
results = connSkt.recv(100)
print('[+] %d/tcp open'% tgtPort)
print('[+] ' + str(results))
connSkt.close()
except:
# if connection fails then print port is closed message
print('[-] %d/tcp closed'% tgtPort)
def portScan(tgtHost, tgtPorts):
try:
# try to get the host by name using socket gethostbyname, if fail print fail message
tgtIP = socket.gethostbyname(tgtHost)
except:
print("[-] Cannot resolve '%s': Uknown host" %tgtHost)
return
try:
# try to resolve the hostname using socket gethostbyaddr with tgtIP, if fail just use the tgtIP
tgtName = socket.gethostbyaddr(tgtIP)
print('\n[+] Scan Results for ' + tgtName[0])
except:
print('\n[+] Scan Results for: ' + tgtIP)
socket.setdefaulttimeout(10)
for tgtPort in tgtPorts:
print('Scanning port ' + tgtPort)
connScan(tgtHost, int(tgtPort))
def main():
tgtHost = input("Enter Host: ")
tgtPorts = input("Enter Port(s) seperated by commas: ")
tgtPorts = str(tgtPorts).split(', ')
if(tgtHost == None) | (tgtPorts[0] == None):
print('[-] You must specify a target host and ports.')
exit(0)
portScan(tgtHost, tgtPorts)
if __name__ == '__main__':
main()