Python实现网络端口转发和重定向的方法
作者:RQSLT 时间:2023-09-23 10:19:59
本文实例讲述了Python实现网络端口转发和重定向的方法。分享给大家供大家参考,具体如下:
【任务】
需要将某个网络端口转发到另一个主机(forwarding),但可能会是不同的端口(redirecting)。
【解决方案】
两个使用threading和socket模块的类就能完成我们需要的端口转发和重定向。
#encoding=utf8
#author: walker摘自《Python Cookbook(2rd)》
#date: 2015-06-11
#function: 网络端口的转发和重定向(适用于python2/python3)
import sys, socket, time, threading
LOGGING = True
loglock = threading.Lock()
#打印日志到标准输出
def log(s, *a):
if LOGGING:
loglock.acquire()
try:
print('%s:%s' % (time.ctime(), (s % a)))
sys.stdout.flush()
finally:
loglock.release()
class PipeThread(threading.Thread):
pipes = [] #静态成员变量,存储通讯的线程编号
pipeslock = threading.Lock()
def __init__(self, source, sink):
#Thread.__init__(self) #python2.2之前版本适用
super(PipeThread, self).__init__()
self.source = source
self.sink = sink
log('Creating new pipe thread %s (%s -> %s)',
self, source.getpeername(), sink.getpeername())
self.pipeslock.acquire()
try:
self.pipes.append(self)
finally:
self.pipeslock.release()
self.pipeslock.acquire()
try:
pipes_now = len(self.pipes)
finally:
self.pipeslock.release()
log('%s pipes now active', pipes_now)
def run(self):
while True:
try:
data = self.source.recv(1024)
if not data:
break
self.sink.send(data)
except:
break
log('%s terminating', self)
self.pipeslock.acquire()
try:
self.pipes.remove(self)
finally:
self.pipeslock.release()
self.pipeslock.acquire()
try:
pipes_left = len(self.pipes)
finally:
self.pipeslock.release()
log('%s pipes still active', pipes_left)
class Pinhole(threading.Thread):
def __init__(self, port, newhost, newport):
#Thread.__init__(self) #python2.2之前版本适用
super(Pinhole, self).__init__()
log('Redirecting: localhost: %s->%s:%s', port, newhost, newport)
self.newhost = newhost
self.newport = newport
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.bind(('', port))
self.sock.listen(5) #参数为timeout,单位为秒
def run(self):
while True:
newsock, address = self.sock.accept()
log('Creating new session for %s:%s', *address)
fwd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
fwd.connect((self.newhost, self.newport))
PipeThread(newsock, fwd).start() #正向传送
PipeThread(fwd, newsock).start() #逆向传送
if __name__ == '__main__':
print('Starting Pinhole port fowarder/redirector')
try:
port = int(sys.argv[1])
newhost = sys.argv[2]
try:
newport = int(sys.argv[3])
except IndexError:
newport = port
except (ValueError, IndexError):
print('Usage: %s port newhost [newport]' % sys.argv[0])
sys.exit(1)
#sys.stdout = open('pinhole.log', 'w') #将日志写入文件
Pinhole(port, newhost, newport).start()
【讨论】
当你在管理一个网络时,即使是一个很小的网络,端口转发和重定向的功能有时也能给你很大的帮助。一些不在你的控制之下的应用或者服务可能是以硬连接的方式接入到某个特定的服务器的地址或端口。通过插入转发和重定向,你就能将对应用的连接请求发送到其他更合适的主机或端口上。
希望本文所述对大家Python程序设计有所帮助。
标签:Python,端口转发,重定向
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Django框架 querySet功能解析
2021-02-15 16:32:14
SQL语句练习实例之四 找出促销活动中销售额最高的职员
2011-11-03 16:47:03
纯js实现遮罩层效果原理分析
2024-02-24 01:32:14
Navicat Premium15连接云服务器中的数据库问题及遇到坑
2024-01-19 05:41:50
![](https://img.aspxhome.com/file/2023/2/77212_0s.png)
用asp编写文档搜索页面
2008-01-13 07:04:00
利用Python Matlab绘制曲线图的简单实例
2021-05-16 07:21:38
![](https://img.aspxhome.com/file/2023/4/78494_0s.png)
php使用curl获取https请求的方法
2023-11-17 11:46:49
ThinkPHP 3.2.3实现页面静态化功能的方法详解
2023-11-23 13:12:53
Python多进程协作模拟实现流程
2021-07-01 17:52:38
python scatter函数用法实例详解
2021-12-17 11:51:50
![](https://img.aspxhome.com/file/2023/4/101434_0s.png)
详解Pandas与openpyxl库的超强结合
2021-09-05 03:52:15
![](https://img.aspxhome.com/file/2023/4/120434_0s.png)
利用 Python 实现多任务进程
2023-12-19 02:53:52
![](https://img.aspxhome.com/file/2023/2/93882_0s.png)
js验证表单(form)中多选框(checkbox)值
2008-03-18 13:39:00
windows10系统中安装python3.x+scrapy教程
2022-06-03 22:27:48
![](https://img.aspxhome.com/file/2023/2/123832_0s.png)
sqlserver数据库优化解析(图文剖析)
2024-01-17 08:55:37
![](https://img.aspxhome.com/file/2023/8/98008_0s.jpg)
MySQL中order by排序语句的原理解析
2024-01-24 15:43:23
![](https://img.aspxhome.com/file/2023/2/124552_0s.png)
Python基于Tensorflow2.X实现汽车油耗预测
2021-05-05 05:25:22
![](https://img.aspxhome.com/file/2023/3/72743_0s.png)
python scrapy框架中Request对象和Response对象的介绍
2021-04-02 07:29:59
![](https://img.aspxhome.com/file/2023/6/95326_0s.png)
如何解决ASP脚本运行超时的错误
2007-10-14 11:38:00
[翻译]标记语言和样式手册 Chapter 11 打印样式
2008-02-11 18:44:00
![](https://img.aspxhome.com/file/UploadPic/20082/11/2008211185712733s.jpg)