Port scanning function implemented in Python

不言
Release: 2018-04-09 14:42:56
Original
1986 people have browsed it

This article mainly introduces the port scanning function implemented in Python. I will share it with you here. Friends who need it can refer to it

The examples in this article describe the port scanning function implemented in Python. Share it with everyone for your reference, the details are as follows:

一码


##

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])
Copy after login


Second operation result

starting 192.168.0.105...

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

Related recommendations:


Python implements the method of using a generator to implement iterable objects

Example of HMacMD5 encryption algorithm implemented in Python_python

The above is the detailed content of Port scanning function implemented in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!