基于Python的端口扫描器

本例是一个基于Python(2.7.x)的简易端口扫描器。基本的想法是这样的:
构建两个函数:connScan()和portScan(),其中connScan()是用于连接指定的地址以及指定端口,建立连接发送信息,看是否有返回信息以确定端口是否开放。portScan()用于获取主机名,打印,调用connScan()进行扫描。
使用Python编写是十分简便的。Python的库十分丰富,很多操作都有现成的库函数调用,完成一个复杂操作只需寥寥数行代码即可。
考虑到在portScan()中将创建线程调用connScan()进行扫描,由于线程同步导致扫描不同端口输出的次序会乱掉,因此设置一个信号量Semaphore,用来在输出时锁定线程,保证端口扫描输出依次打印。

screenLock = Semaphore(value = 1) #定义一个信号量用于锁定线程
def connScan(tgtHost, tgtPort):
  try:
    connSkt = socket(AF_INET, SOCK_STREAM)
    connSkt.connect((tgtHost, tgtPort)) #连接指定的地址和端口
    connSkt.send('ViolentPython\r\n') #发送消息
    results = connSkt.recv(100) #若端口开放,记录返回的消息
    screenLock.acquire() #Lock锁定线程
    print '[+]%d/tcp open'% tgtPort
    print '[+] ' + str(results)
  except:
    screenLock.acquire()
    print '[-] %d/tcp closed'% tgtPort
  finally:
    screenLock.release() #解锁线程
    connSkt.close()

portScan()函数如下:

def portScan(tgtHost,tgtPorts):
  try:
    tgtIP = gethostbyname(tgtHost)
  except:
    print "[-] Cannot resolve '%s': Unknown host" %tgtHost
    return
  try:
    tgtName = gethostbyaddr(tgtIP)
    print '\n[+] Scan Results for:' + tgtName[0]
  except:
    print '\n[+] Scan Results for:' +tgtIP
  setdefaulttimeout(1) #时间戳
  for tgtPort in tgtPorts: 
    t = Thread(target = connScan, args=(tgtHost, int(tgtPort))) #创建线程,调用connScan()
    t.start()

附上源代码:

import optparse
from socket import *
from threading import *

screenLock = Semaphore(value = 1)
def connScan(tgtHost, tgtPort):
  try:
    connSkt = socket(AF_INET, SOCK_STREAM)
    connSkt.connect((tgtHost, tgtPort))
    connSkt.send('ViolentPython\r\n')
    results = connSkt.recv(100)
    screenLock.acquire()
    print '[+]%d/tcp open'% tgtPort
    print '[+] ' + str(results)
  except:
    screenLock.acquire()
    print '[-] %d/tcp closed'% tgtPort
  finally:
    screenLock.release()
    connSkt.close()


def portScan(tgtHost,tgtPorts):
  try:
    tgtIP = gethostbyname(tgtHost)
  except:
    print "[-] Cannot resolve '%s': Unknown host" %tgtHost
    return
  try:
    tgtName = gethostbyaddr(tgtIP)
    print '\n[+] Scan Results for:' + tgtName[0]
  except:
    print '\n[+] Scan Results for:' +tgtIP
  setdefaulttimeout(1)
  for tgtPort in tgtPorts:
    t = Thread(target = connScan, args=(tgtHost, int(tgtPort))) #set a thread
    t.start()

def main():
  parser = optparse.OptionParser("usage%prog"+\
    "-H  -p ") 
    '''
    调用optparse.OptionParser([usage message])方法生成一个  
    参数解析器类的实例。
    '''
  parser.add_option('-H', dest = 'tgtHost', type = 'string', \
    help = 'specify target host')
  parser.add_option('-p', dest = 'tgtPort', type = 'string', \
    help = 'specify target port[s] separated by comma')
  (options,args) = parser.parse_args()
  tgtHost = options.tgtHost
  tgtPorts = str(options.tgtPort).split(',')
  if(tgtHost == None) | (tgtPorts[0] == None):
    print parser.usage
    exit(0)
  portScan(tgtHost, tgtPorts)

if __name__ == '__main__':
  main()

运行示例:
基于Python的端口扫描器_第1张图片

(得益于《Python绝技:运用Python成为顶级黑客》的指导([美]TJ.O’Connor 著))。

你可能感兴趣的:(UNIX编程,python脚本)