Home Backend Development Python Tutorial Python实现TCP协议下的端口映射功能的脚本程序示例

Python实现TCP协议下的端口映射功能的脚本程序示例

Jun 16, 2016 am 08:47 AM
python tcp port

1 端口映射

举个例子来说明一下端口映射的作用。

有A、B、C三台计算机,A、B互通,B、C互通,但是A、C不通,这个时候在C上开了一个Web服务,如何让A访问C的Web服务?

最简单有效的办法就是在B上开一个端口映射服务,然后让A访问B的某个端口,B将这个端口上的所有流量全部转发到C的Web服务端口上,同时将C上Web服务返回的流量也全部转发给A。这样对A来说,以B为跳板,实现了间接访问C上Web服务的目的。

2 实现流程

端口映射的原理并不复杂,本文以TCP为例介绍一下实现过程,简单画了个时序图(如下),这里就不再用文字赘述了。

2016614171010464.png (471×754)

需要注意的是,由于端口映射只是单纯的流量转发,对应用层数据不进行处理,所以对于多通道协议是无法支持的(如FTP协议)。

3 代码示例

按照上面的流程,Python实现如下(建议从后向前看):

# -*- coding: utf-8 -*-
# tcp mapping created by hutaow(hutaow.com) at 2014-08-31

import socket
import threading

# 端口映射配置信息
CFG_REMOTE_IP = '192.168.0.10'
CFG_REMOTE_PORT = 22
CFG_LOCAL_IP = '0.0.0.0'
CFG_LOCAL_PORT = 10022

# 接收数据缓存大小
PKT_BUFF_SIZE = 2048

# 调试日志封装
def send_log(content):
  print content
  return

# 单向流数据传递
def tcp_mapping_worker(conn_receiver, conn_sender):
  while True:
    try:
      data = conn_receiver.recv(PKT_BUFF_SIZE)
    except Exception:
      send_log('Event: Connection closed.')
      break

    if not data:
      send_log('Info: No more data is received.')
      break

    try:
      conn_sender.sendall(data)
    except Exception:
      send_log('Error: Failed sending data.')
      break

    # send_log('Info: Mapping data > %s ' % repr(data))
    send_log('Info: Mapping > %s -> %s > %d bytes.' % (conn_receiver.getpeername(), conn_sender.getpeername(), len(data)))

  conn_receiver.close()
  conn_sender.close()

  return

# 端口映射请求处理
def tcp_mapping_request(local_conn, remote_ip, remote_port):
  remote_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

  try:
    remote_conn.connect((remote_ip, remote_port))
  except Exception:
    local_conn.close()
    send_log('Error: Unable to connect to the remote server.')
    return

  threading.Thread(target=tcp_mapping_worker, args=(local_conn, remote_conn)).start()
  threading.Thread(target=tcp_mapping_worker, args=(remote_conn, local_conn)).start()

  return

# 端口映射函数
def tcp_mapping(remote_ip, remote_port, local_ip, local_port):
  local_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  local_server.bind((local_ip, local_port))
  local_server.listen(5)

  send_log('Event: Starting mapping service on ' + local_ip + ':' + str(local_port) + ' ...')

  while True:
    try:
      (local_conn, local_addr) = local_server.accept()
    except KeyboardInterrupt, Exception:
      local_server.close()
      send_log('Event: Stop mapping service.')
      break

    threading.Thread(target=tcp_mapping_request, args=(local_conn, remote_ip, remote_port)).start()

    send_log('Event: Receive mapping request from %s:%d.' % local_addr)

  return

# 主函数
if __name__ == '__main__':
  tcp_mapping(CFG_REMOTE_IP, CFG_REMOTE_PORT, CFG_LOCAL_IP, CFG_LOCAL_PORT)

Copy after login

4 运行

运行效果如下,192.168.0.20通过连接映射服务器的10022端口,成功访问192.168.0.10的SSH服务(22端口):

2016614171059596.png (640×436)

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

See all articles