search
HomeBackend DevelopmentPython TutorialPython实现TCP/IP协议下的端口转发及重定向示例

首先,我们用webpy写一个简单的网站,监听8080端口,返回“Hello, EverET.org”的页面。

然后我们使用我们的forwarding.py,在80端口和8080端口中间建立两条通信管道用于双向通信。

此时,我们通过80端口访问我们的服务器。

浏览器得到:

2016614172131520.png (426×190)

然后,我们在forwarding.py的输出结果中可以看到浏览器和webpy之间的通信内容。

2016614172157520.png (675×588)

代码:

#!/usr/bin/env python
import sys, socket, time, threading

loglock = threading.Lock()
def log(msg):
  loglock.acquire()
  try:
    print '[%s]: \n%s\n' % (time.ctime(), msg.strip())
    sys.stdout.flush()
  finally:
    loglock.release()

class PipeThread(threading.Thread):
  def __init__(self, source, target):
    threading.Thread.__init__(self)
    self.source = source
    self.target = target

  def run(self):
    while True:
      try:
        data = self.source.recv(1024)
        log(data)
        if not data: break
        self.target.send(data)
      except:
        break
    log('PipeThread done')

class Forwarding(threading.Thread):
  def __init__(self, port, targethost, targetport):
    threading.Thread.__init__(self)
    self.targethost = targethost
    self.targetport = targetport
    self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.sock.bind(('0.0.0.0', port))
    self.sock.listen(10)
  def run(self):
    while True:
      client_fd, client_addr = self.sock.accept()
      target_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      target_fd.connect((self.targethost, self.targetport))
      log('new connect')
      # two direct pipe
      PipeThread(target_fd, client_fd).start()
      PipeThread(client_fd, target_fd).start()


if __name__ == '__main__':
  print 'Starting'
  import sys
  try:
    port = int(sys.argv[1])
    targethost = sys.argv[2]
    try: targetport = int(sys.argv[3])
    except IndexError: targetport = port
  except (ValueError, IndexError):
    print 'Usage: %s port targethost [targetport]' % sys.argv[0]
    sys.exit(1)

  #sys.stdout = open('forwaring.log', 'w')
  Forwarding(port, targethost, targetport).start()

Statement
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
How do you append elements to a Python array?How do you append elements to a Python array?Apr 30, 2025 am 12:19 AM

InPython,youappendelementstoalistusingtheappend()method.1)Useappend()forsingleelements:my_list.append(4).2)Useextend()or =formultipleelements:my_list.extend(another_list)ormy_list =[4,5,6].3)Useinsert()forspecificpositions:my_list.insert(1,5).Beaware

How do you debug shebang-related issues?How do you debug shebang-related issues?Apr 30, 2025 am 12:17 AM

The methods to debug the shebang problem include: 1. Check the shebang line to make sure it is the first line of the script and there are no prefixed spaces; 2. Verify whether the interpreter path is correct; 3. Call the interpreter directly to run the script to isolate the shebang problem; 4. Use strace or trusts to track the system calls; 5. Check the impact of environment variables on shebang.

How do you remove elements from a Python array?How do you remove elements from a Python array?Apr 30, 2025 am 12:16 AM

Pythonlistscanbemanipulatedusingseveralmethodstoremoveelements:1)Theremove()methodremovesthefirstoccurrenceofaspecifiedvalue.2)Thepop()methodremovesandreturnsanelementatagivenindex.3)Thedelstatementcanremoveanitemorslicebyindex.4)Listcomprehensionscr

What data types can be stored in a Python list?What data types can be stored in a Python list?Apr 30, 2025 am 12:07 AM

Pythonlistscanstoreanydatatype,includingintegers,strings,floats,booleans,otherlists,anddictionaries.Thisversatilityallowsformixed-typelists,whichcanbemanagedeffectivelyusingtypechecks,typehints,andspecializedlibrarieslikenumpyforperformance.Documenti

What are some common operations that can be performed on Python lists?What are some common operations that can be performed on Python lists?Apr 30, 2025 am 12:01 AM

Pythonlistssupportnumerousoperations:1)Addingelementswithappend(),extend(),andinsert().2)Removingitemsusingremove(),pop(),andclear().3)Accessingandmodifyingwithindexingandslicing.4)Searchingandsortingwithindex(),sort(),andreverse().5)Advancedoperatio

How do you create multi-dimensional arrays using NumPy?How do you create multi-dimensional arrays using NumPy?Apr 29, 2025 am 12:27 AM

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

Explain the concept of 'broadcasting' in NumPy arrays.Explain the concept of 'broadcasting' in NumPy arrays.Apr 29, 2025 am 12:23 AM

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

Explain how to choose between lists, array.array, and NumPy arrays for data storage.Explain how to choose between lists, array.array, and NumPy arrays for data storage.Apr 29, 2025 am 12:20 AM

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

See all articles

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.