port scan

Gerhard =?unknown-8bit?Q?H=E4ring?= gh_pythonlist at gmx.de
Tue Apr 9 20:05:00 EDT 2002


* distrex <distrex at hotmail.com> [2002-04-09 15:10 -0700]:
> I don't know if this is possible but is there a way to create a port
> scanner in python?

If by a port scanner you only want to scan for open ports, this is
surely possible, and not difficult, either. Simply try to connect to the
port, if this succeeds, you've found an open port. This is a minimal
example for a Python portscanner (only checks for TCP so far):

#!/usr/bin/env python
import sys, socket

def checkPortTCP(host, port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.connect((host, port))
        return 1
    except socket.error, reason:
        return 0

def main():
    hostname = sys.argv[1]

    port_range = range(1024)
    open_ports = []
    for port in port_range:
        if checkPortTCP(hostname, port):
            open_ports.append(port)
    print open_ports

if __name__ == "__main__":
    main()

I recommend to look into the documentation of the socket module, and if
this looks like chinese to you, as it was to me, the Socket Programming
HOWTO at http://py-howto.sf.net/

Gerhard
-- 
This sig powered by Python!
Außentemperatur in München: 3.0 °C      Wind: 2.4 m/s





More information about the Python-list mailing list