做一个战士不是一件简单的事,这是一件无休止的,会持续到我们生命最后一刻的斗争。没有人生下来就是战士,就像没人生下来就注定庸碌,是我们让自己变成这样或者那样!
——夏目漱石

设计思路:
调用optparse.OptionParse()方法,构建选项分析器,接受主机名(或者IP地址),扫描的端口列表两个参数。构建两个函数PortScan和ConnScan,PortScan解析主机名成IP地址,然后枚举端口列表中的每个端口用ConnScan函数尝试连接主机,打印扫描端口的信息。

主函数代码:

def main():
        parser = optparse.OptionParser('usage %prog -H  -p ')
        parser.add_option('-H',dest='tgtHost',type='string',
        help='specify target host')
        parser.add_option('-p',dest='tgtPort',type='int',
        help='specify target port')
        (options,args) = parser.parse_args()
        tgtHost = options.tgtHost
        tgtPort = options.tgtPort
        args.append(tgtPort)
        if (tgtHost == None) | (tgtPort == None):
                print(parser.usage)
                exit(0)
        portScan(tgtHost,args)

PortScann函数代码:

def portScan(tgtHost,tgtPorts):
        try:
                tgtIP = socket.gethostbyname(tgtHost)
        except:
                print("[-]Cannot resolve '%s':Unkown host" % tgtHost)
                return
        try:
                tgtName = socket.gethostbyaddr(tgtIP)
                print('\n[+]Scan Result for:'+ tgtName[0])
        except:
                print('\n[+]Scan Result for:'+ tgtIP)
        socket.setdefaulttimeout(1)
        for tgtPort in tgtPorts:
                print('Scanning port' + str(tgtPort))
                connScan(tgtHost,int(tgtPort))

ConnScan函数代码:

def connScan(tgtHost,tgtPort):
        try:
                connSkt = s
                                ocket.socket(socket.AF_INET,socket.SOCK_STREAM)
                connSkt.connect((tgtHost,tgtPort))
                connSkt.send('ViolenPython\r\n')
                results = connSkt.recv(100)
                print('[+]%d/tcp open' % tgtPort)
                print('[+]'+str(results))
                connSkt.close()
        except:
                print('[-]%d/tcp closed' % tgtPort)
**结合nmap扫描端口设计思路**
导入nmap库,并且构建一个Scan()函数,接收主机地址IP和需要扫描的端口号。然后创建一个PortScanner()类的实例运行基本的nmap扫描。

**关键代码**
```
def nmapScan(tgthost,tgtport):
    nmScan = nmap.PortScanner()
    results = nmScan.scan(tgthost,tgtport)
    state = results['scan'][tgthost]['tcp'][int(tgtport)]['state']
    print('[*]'+tgthost+" tcp/"+tgtport+" "+state)
```