python实现端口转发器的方法


Posted in Python onMarch 13, 2015

本文实例讲述了python实现端口转发器的方法。分享给大家供大家参考。具体如下:

下面的python代码实现端口转发器,支持udp端口转发

由于工作需要用到一个端口转发器,并且要求支持TCP和UDP协议。在网上找了蛮久,但没有中意的。于是就自己写了一个。这个转发器是基于python cookbook的一个示例改写的,原先的这个示例只支持TCP协议,我这里增加了UDP协议的支持,程序写的不怎么好,不过它确实能用!

portmap.py代码如下:

#-* -coding: UTF-8 -* -

'''

Created on 2012-5-8

@author: qh

'''

import time,socket,threading

def log(strLog):

    strs=time.strftime("%Y-%m-%d %H:%M:%S")

    print strs+"->"+strLog

class pipethread(threading.Thread):

    '''

    classdocs

    '''

    def __init__(self,source,sink):

        '''

        Constructor

        '''

        threading.Thread.__init__(self)

        self.source=source

        self.sink=sink

        log("New Pipe create:%s->%s" % (self.source.getpeername(),self.sink.getpeername()))

    def run(self):

        while True:

            try:

                data=self.source.recv(1024)

                if not data: break

                self.sink.send(data)

            except Exception ,ex:

                log("redirect error:"+str(ex))

                break

        self.source.close()

        self.sink.close()

class portmap(threading.Thread):

    def __init__(self,port,newhost,newport,local_ip=''):

        threading.Thread.__init__(self)

        self.newhost=newhost

        self.newport=newport

        self.port=port

        self.local_ip=local_ip

        self.sock=None

        self.sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

        self.sock.bind((self.local_ip,port))

        self.sock.listen(5)

        log("start listen protocol:%s,port:%d " % ('tcp',port))

    def run(self):

        while True:

            fwd=None

            newsock=None

            newsock,address=self.sock.accept()

            log("new connection->protocol:%s,local port:%d,remote address:%s" % ('tcp',self.port,address[0]))

            fwd=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

            try:

                fwd.connect((self.newhost,self.newport))

            except Exception ,ex:

                log("connet newhost error:"+str(ex))

                break

            p1=pipethread(newsock,fwd,self.protocol)

            p1.start()

            p2=pipethread(fwd,newsock,self.protocol)

            p2.start()

class pipethreadUDP(threading.Thread):

    def __init__(self,connection,connectionTable,table_lock):

        threading.Thread.__init__(self)

        self.connection=connection

        self.connectionTable=connectionTable

        self.table_lock=table_lock

        log('new thread for new connction')

    def run(self):

        while True:

            try:

                data,addr=self.connection['socket'].recvfrom(4096)

                #log('recv from addr"%s' % str(addr))

            except Exception ,ex:

                log("recvfrom error:"+str(ex))

                break

            try:

                self.connection['lock'].acquire()

                self.connection['Serversocket'].sendto(data,self.connection['address'])

                #log('sendto address:%s' % str(self.connection['address']))

            except Exception ,ex:

                log("sendto error:"+str(ex))

                break

            finally:self.connection['lock'].release()

            self.connection['time']=time.time()

        self.connection['socket'].close()

        log("thread exit for: %s" % str(self.connection['address']))

        self.table_lock.acquire()

        self.connectionTable.pop(self.connection['address'])

        self.table_lock.release()

        log('Release udp connection for timeout:%s' % str(self.connection['address']))

class portmapUDP(threading.Thread):

    def __init__(self,port,newhost,newport,local_ip=''):

        threading.Thread.__init__(self)

        self.newhost=newhost

        self.newport=newport

        self.port=port

        self.local_ip=local_ip

        self.sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

        self.sock.bind((self.local_ip,port))

        self.connetcTable={}

        self.port_lock=threading.Lock()

        self.table_lock=threading.Lock()

        self.timeout=300

        #ScanUDP(self.connetcTable,self.table_lock).start()

        log('udp port redirect run->local_ip:%s,local_port:%d,remote_ip:%s,remote_port:%d' % (local_ip,port,newhost,newport))

    def run(self):

        while True:

            data,addr=self.sock.recvfrom(4096)

            connection=None

            newsock=None

            self.table_lock.acquire()

            connection=self.connetcTable.get(addr)

            newconn=False

            if connection is None:

                connection={}

                connection['address']=addr

                newsock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

                newsock.settimeout(self.timeout)

                connection['socket']=newsock

                connection['lock']=self.port_lock

                connection['Serversocket']=self.sock

                connection['time']=time.time()

                newconn=True

                log('new connection:%s' % str(addr))

            self.table_lock.release()

            try:

                connection['socket'].sendto(data,(self.newhost,self.newport))

            except Exception ,ex:

                log("sendto error:"+str(ex))

                #break

            if newconn:

                self.connetcTable[addr]=connection

                t1=pipethreadUDP(connection,self.connetcTable,self.table_lock)

                t1.start()

        log('main thread exit')

        for key in self.connetcTable.keys():

            self.connetcTable[key]['socket'].close()

if __name__=='__main__':

    myp=portmapUDP(10061,'10.0.1.29',161)

    myp.start()

    #myp.__stop()

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

Python 相关文章推荐
python thread 并发且顺序运行示例
Apr 09 Python
Python实现的爬虫功能代码
Jun 24 Python
pycharm 解除默认unittest模式的方法
Nov 30 Python
详解Appium+Python之生成html测试报告
Jan 04 Python
pytorch中的embedding词向量的使用方法
Aug 18 Python
python英语单词测试小程序代码实例
Sep 09 Python
Python 复平面绘图实例
Nov 21 Python
PyTorch 普通卷积和空洞卷积实例
Jan 07 Python
python实现百度OCR图片识别过程解析
Jan 17 Python
Python3+RIDE+RobotFramework自动化测试框架搭建过程详解
Sep 23 Python
Python利用Pillow(PIL)库实现验证码图片的全过程
Oct 04 Python
python文件名批量重命名脚本实例代码
Apr 22 Python
python实现超简单端口转发的方法
Mar 13 #Python
python简单程序读取串口信息的方法
Mar 13 #Python
python通过BF算法实现关键词匹配的方法
Mar 13 #Python
python通过装饰器检查函数参数数据类型的方法
Mar 13 #Python
python实现简单温度转换的方法
Mar 13 #Python
python实现简单socket程序在两台电脑之间传输消息的方法
Mar 13 #Python
Python比较两个图片相似度的方法
Mar 13 #Python
You might like
php截取utf-8中文字符串乱码的解决方法
2010/03/29 PHP
Yii使用DeleteAll连表删除出现报错问题的解决方法
2016/07/14 PHP
php中foreach结合curl实现多线程的方法分析
2016/09/22 PHP
PHP xpath()函数讲解
2019/02/11 PHP
Mootools 1.2教程 类(一)
2009/09/15 Javascript
Ajax 数据请求的简单分析
2011/04/05 Javascript
解析Javascript中中括号“[]”的多义性
2013/12/03 Javascript
JavaScript中String.prototype用法实例
2015/05/20 Javascript
详述JavaScript实现继承的几种方式(推荐)
2016/03/22 Javascript
全屏滚动插件fullPage.js使用实例解析
2016/10/21 Javascript
Javascript 函数的四种调用模式
2016/11/05 Javascript
jQuery延迟执行的实现方法
2016/12/21 Javascript
解决vue2.x中数据渲染以及vuex缓存的问题
2017/07/13 Javascript
Vue框架之goods组件开发详解
2018/01/25 Javascript
用jQuery将JavaScript对象转换为querystring查询字符串的方法
2018/11/12 jQuery
详解Vue中watch的详细用法
2018/11/28 Javascript
微信小程序学习笔记之本地数据缓存功能详解
2019/03/29 Javascript
实现elementUI表单的全局验证的方法步骤
2019/04/29 Javascript
Typescript的三种运行方式(小结)
2019/09/18 Javascript
浅谈关于vue中scss公用的解决方案
2019/12/02 Javascript
Vue单文件组件开发实现过程详解
2020/07/30 Javascript
使用C语言扩展Python程序的简单入门指引
2015/04/14 Python
你真的了解Python的random模块吗?
2017/12/12 Python
Python GUI布局尺寸适配方法
2018/10/11 Python
Python类中方法getitem和getattr详解
2019/08/30 Python
在Python中画图(基于Jupyter notebook的魔法函数)
2019/10/28 Python
Python模拟登录requests.Session应用详解
2020/11/17 Python
Html5 postMessage实现跨域消息传递
2016/03/11 HTML / CSS
John Hardy官方网站:手工设计首饰的奢侈品牌
2017/07/05 全球购物
英国床垫和床架购物网站:Bedman
2019/11/04 全球购物
意大利在线高尔夫商店:Online Golf
2021/03/09 全球购物
财务会计应届生求职信
2013/11/24 职场文书
2014年班级工作总结范文
2014/12/23 职场文书
写给老婆的保证书
2015/02/27 职场文书
首席执行官观后感
2015/06/03 职场文书
高中语文教学反思范文
2016/02/16 职场文书