做一个战士不是一件简单的事,这是一件无休止的,会持续到我们生命最后一刻的斗争。没有人生下来就是战士,就像没人生下来就注定庸碌,是我们让自己变成这样或者那样!
——夏目漱石
设计思路:
调用optparse.OptionParse()方法,构建选项分析器,接受主机名(或者IP地址),扫描的端口列表两个参数。构建两个函数PortScan和ConnScan,PortScan解析主机名成IP地址,然后枚举端口列表中的每个端口用ConnScan函数尝试连接主机,打印扫描端口的信息。
主函数代码:
def main():
parser = optparse.OptionParser(‘usage %prog -H <target host> -p <target port>‘)
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 = socket.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)
原文地址:http://blog.51cto.com/mbb97/2059864
时间: 2024-10-13 14:08:22