当前位置:编程学习 > python >>

python代码扫描端口方法

本文为学习python的socket时候所写,当然python用来扫描端口的效率并不高,这里仅仅是为了study。

#!/usr/bin/env python

import socket

def check_server(address,port):
    s=socket.socket()
    try:
        s.connect((address,port))
        return True
    except socket.error,e:
        return False
   
if __name__==__main__:
    from optparse import OptionParser
    parser=OptionParser()
    parser.add_option("-a","--address",dest="address",default=localhost,help="Address for server",metavar="ADDRESS")
    parser.add_option("-s","--start",dest="start_port",type="int",default=1,help="start port",metavar="SPORT")
    parser.add_option("-e","--end",dest="end_port",type="int",default=1,help="end port",metavar="EPORT")
    (options,args)=parser.parse_args()
    print options: %s, args: %s % (options, args)
    port=options.start_port
    while(port<=options.end_port):
        check = check_server(options.address, port)
        if (check):
            print Port  %s is on % port
        port=port 1

不过好像没有看到python中有加加运算符号。这里代码在ubuntu 9.04中调试通过。

# ./port_scan.py -h
Usage: port_scan.py [options]

Options:
  -h, --help            show this help message and exit
  -a ADDRESS, --address=ADDRESS
                        Address for server
  -s SPORT, --start=SPORT
                        start port
  -e EPORT, --end=EPORT
                        end port

# ./port_scan.py -a 192.168.1.1 -s 1 -e 100
options: {end_port: 100, start_port: 1, address: 192.168.1.1}, args: []
Port  21 is on
Port  23 is on
Port  80 is on
补充:Web开发 , Python ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,