python检测主机存活端口

发布时间:2019-09-11 07:45:00编辑:auto阅读(1583)

    监测主机存活的端口

    #!/usr/bin/env python
    # coding-utf8
    import argparse
    import socket
    import sys
    
    #author: wolf_ribble
    
    def scan_ports(host,start_port,end_port):
        """Scan remote hosts"""
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except socket.error,error_msg:
            print 'Socket creation failed.Error code:' + str(error_msg[0]) + 'Erroe message:' + error_msg[1]
            sys.exit()
    
        try:
            remote_ip = socket.gethostbyname(host)
        except socket.error,error_msg:
            print error_msg
            sys.exit()
    
        end_port +=1
        for port in range(start_port,end_port):
            try:
                sock.connect((remote_ip,port))
                print 'Port' + str(port) + 'is ipen'
    
                sock.close()
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
            except socket.error,error_msg:
                #print error_msg
                pass
    
    if __name__ == '__main__':
        parser = argparse.ArgumentParser(description='remote port scaner')
        parser.add_argument('--host',action="store",dest="host",default='www.wealink.com')
        parser.add_argument('--start-port',action="store",dest="start_port",default='1',type=int)
        parser.add_argument('--end-port',action="store",dest="end_port",default='100',type=int)
        given_args = parser.parse_args()
        host, start_port ,end_start = given_args.host , given_args.start_port,given_args.end_port
    
        scan_ports(host,start_port,end_start)



关键字