Python – Scan network for a specific service and send a string via socket to obtain more information about the running service.

The script below uses the netaddr, nmap module and socket module. The netaddr module calculate the IP range you want to scan, the nmap module does the scan it self. The socket module will send a string of text in order to obtain more information regarding the service running.

The service being scanned is the SSH service. In this case it is hardcoded to scan that specific service.

import nmap
from netaddr import IPNetwork
import socket
from contextlib import contextmanager


nm = nmap.PortScanner()


for loop_1 in IPNetwork('10.0.0.2/26'):
#for loop_1 in IPNetwork('10.0.0.29'):
    (nm.scan(loop_1.format(), '22'))
    try:

       state = (nm[loop_1.format()]['tcp'][22]['state'])

       server_address = (loop_1.format(),22)
       sckt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
       sckt.connect((server_address))
       sckt.send('I AM TEXT')
       reply = sckt.recv(100)
       sckt.shutdown
       sckt.close()

       if state == "open" and reply:

            data = [loop_1, state, reply]
            print ""
            print "Server-------SSH------Version"
            print data[0], "  ", data[1],"   ", data[2]
       else:
            print "Nooo"

    except (KeyError) as ip_not_reached:
        pass

    except (socket.error) as socket_connection_error:
        print ""
        print loop_1,socket_connection_error
Share Button