Python and Networking Questions

closed account (3qX21hU5)
So it's slow today at work and decided to play around with Python a bit and make a little port scanner. Which I believe works fine (Though can't test it since my work's IDS will start getting mad at me if I go around scanning) but have a few questions if anyone with either networking experience, threading experience or Python experience could help.

First how do you go about getting the information about what is running on that open port(Would what I have below work fine)? From a little research I believe it is the ports "banner" if I am not mistaken... How do you go about getting the banner? Do you just connect to the port and try and receive something from it? Or do you need to send something first then receive the response?

Second question is in my code below would the Thread module work better then the multiprocessing module for this task? From what I read the Thread module isn't exactly multithreading like in C++ it is just creating virtual "threads" and not actually using multiple cores. Whereas the multiprocessing module does(?) use multiple cores?

I am just curious what the differences are between the two and when to use either of them. I am thinking that the Thread module might work better in this case since it isn't limited by the CPU and the task in my program isn't about processing a bunch of data but instead waiting for I/O (Waiting for the sockets to get the info or timeout) so using multiple cores wouldn't matter (I don't think at least)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# Simple port scanner which uses multiprocessing

import socket
import argparse
from multiprocessing import Pool, cpu_count
from datetime import datetime


# Command line argument parsing stuff
parser = argparse.ArgumentParser()
parser.add_argument('hosts', help = "Taget host(s) to scan" + \
                    " if you have more then one host to scan seperate them by spaces", nargs = '+')
parser.add_argument('-T', dest = 'scanType', help = "Type of scan to do", \
                    choices = ['port', 'banner'], required = True)
parser.add_argument('-P', dest = 'numPorts', help = "Number of ports to scan", \
                    choices = ['all', 'common'], default = "common")
args = parser.parse_args()


def portScan(host, port):
    try:
        portSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        portSocket.settimeout(0.5)
        portSocket.connect((host, port))
        return "[+] Port %d\t= [OPEN]" % port
    except:
        pass
    finally:
        portSocket.close()

        
def bannerScan(host, port):
    try:
        bannerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        bannerSocket.settimeout(1)
        bannerSocket.connect((host, port))
        result = bannerSocket.recv(100)
        return "[+] Port %d\t = %s" % (port, str(result))
    except:
        pass
    finally:
        bannerSocket.close()
        
        
def main():
    startTime = datetime.now()
    
    # Determine the type of scan to run
    if args.scanType.lower() == "port":
        scan = portScan
    else:
        scan = bannerScan
        
    # Determine what ports to scan
    if args.numPorts.lower() == "common":
        ports = [i for i in range(1, 1025)]
    else:
        ports = [i for i in range(1, 65536)]
        
    # Setup the worker pool.
    pool = Pool(processes = cpu_count())
    
    # Run the scans on all the entered hosts
    print '\n\n[*] Scanning Hosts...\n'
    for host in args.hosts:
        results = [pool.apply_async(scan, (host, port)) for port in ports]
        
        print '[*] Results for %s' % host
        for result in filter(lambda i : i.get() != None, results):
            print result.get()
                
    endTime = datetime.now()
    print "\nTotal time to scan: " + str(endTime - startTime)
            
if __name__ == '__main__':
    main()


Anyways thanks in advance for any help.
Last edited on
First how do you go about getting the information about what is running on that open port

I'm useless for question number two so I'll focus on this one. If you're lazy you would try to use netstat, if you're trying to be more "hackery" you should kind of know what you're looking for. For example, to test if the host is running a mail server then you would send "EHLO". Most services have standardized ports that they host from and a lot of these are enumerated on Wikipedia:
http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers

closed account (3qX21hU5)
So every kind of service would have a different command you can send them to have them respond with the Application's name, version number, ect?

Like using your example of a mail server if I sent "EHLO" to port 24 like this
1
2
3
4
bannerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create a socket to use
bannerSocket.connect((host, 24)) # Try connecting to the host on port 24
bannerSocket.send("EHLO") # Send "EHLO"
result = bannerSocket.recv(100) # Receive whatever it sends back 

it would then respond with the application that is running on that system and that port?

There is no "standard" way of asking for what application is running on a port that would work for every port?

Basically what I would like to do with the script I made is be able to scan every open port and return to the user what is running on those ports. But not sure how to go about it (I got the open ports down but not sure how to tell what is running on them).
Last edited on
Technically with a mail server it has to tell you that it is a mail server when you connect to the port (it sends a 220 message to tell you if it is ready or not). Others may be similar, but I know that they all have commands that you send to gather more information then whether the port is open or not.
Last edited on
Just iterate through all of them. Computers are fast these days anyways


trollface.jpg
Topic archived. No new replies allowed.