I'm trying to code a port scanner in python with banner grabbing.
Without the s.send('getBanner\n')
line (which grabs the banner) my script works, and it prints the open ports.
But when I add the 'getBanner'
line, a socket error says '[Errn 32] Broken Pipe'
.
I know that this error probably happens because the clients don't wait till the connection get established and close the socket. How can I solve this?
The code:
import socket
host = '192.168.1.1'
for port in range(1,1024):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex((host, port))
s.send(('getBanner\n'))
banner = s.recv(1024)
if result == 0:
print "[+] Port %s tcp/open" % port
print "[+] Banner: %s" % banner
s.close()
Not all ports have a service listening on them and when they do, you need to follow whatever protocol is normal for that service. I assume you have some sort of service that responds to "getBanner", but most will not. You are connecting to things like FTP, SSH, DNS, NFS and mail servers and these things don't have "getBanner" commands. But you are also trying to connect to ports that don't have anything listening on them and this generates an error.
Looking at the docs:
Your connection call is returning an error code and you need to check that before trying to send the request. So, as a minimum:
But since most servers listening on ports don't respond to a "getBanner" command, its either going to hang or more likely raise connection reset errors.