Python实现的端口扫描功能示例

本文实例讲述了Python实现的端口扫描功能。分享给大家供大家参考,具体如下:

一 代码

import sys
import socket
import multiprocessing
def ports(ports_service):
  #获取常用端口对应的服务名称
  for port in list(range(1,100))+[143,145,113,443,445,3389, 8080]:
    try:
      ports_service[port] = socket.getservbyport(port)
    except socket.error:
      pass
def ports_scan(HOST, ports_service):
  ports_open = []
  try:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #sock.settimeout(60)
  except socket.error:
    print('socket creation error')
    sys.exit()
  for port in ports_service:
    try:
      #尝试连接指定端口
      sock.connect((HOST,port))
      #记录打开的端口
      ports_open.append(port)
      sock.close()
    except socket.error:
      pass
  return ports_open
if __name__=='__main__':
  m = multiprocessing.Manager()
  ports_service = dict()
  results = dict()
  ports(ports_service)
  #创建进程池,允许最多8个进程同时运行
  pool = multiprocessing.Pool(processes=8)
  net = '192.168.0.'
  for host_number in map(str,range(105,106)):
    host = net+host_number
    #创建一个新进程,同时记录其运行结果
    results[host] = pool.apply_async(ports_scan, (host, ports_service))
    print('starting '+host+'...')
  #关闭进程池,close()必须在join()之前调用
  pool.close()
  #等待进程池中的进程全部执行结束
  pool.join()
  #打印输出结果
  for host in results:
    print('='*30)
    print(host,'.'*10)
    for port in results[host].get():
      print(port, ':', ports_service[port])

二 运行结果

starting 192.168.0.105...
==============================
192.168.0.105 ..........
80 : http

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python Socket编程技巧总结》、《Python URL操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

相关推荐