[Python-Twisted] Twisted入門之連接埠轉寄伺服器

來源:互聯網
上載者:User

Twisted 是Python界很有名的一個基於非同步事件的網路I/O架構,效能棒棒的,經曆過BT的考驗。本人垂涎很久了,於是寫了一個連接埠轉寄伺服器,純練手~~~

 

需求:將windows的遠端桌面做一個連接埠轉寄。

即:有三台機器分別為A B C.在C上開啟遠端桌面服務,開啟3389連接埠。

      在B上運行連接埠轉寄程式,將發往B的1099連接埠的資料發送到C的3389.

     這樣在A上通過遠端桌面用戶端訪問B的1099連接埠就可以遠端存取C的機器。

Understand?

let's go !!

Code  :

from twisted.internet.protocol import Protocol,ClientCreator

from twisted.internet import reactor
from twisted.protocols.basic import LineReceiver
from twisted.internet.protocol import Factory,ClientFactory
class Transfer(Protocol):
        def __init__(self):
                pass
        def connectionMade(self):
                c = ClientCreator(reactor,Clienttransfer)
                c.connectTCP("10.61.1.243",3389).addCallback(self.set_protocol)
                self.transport.pauseProducing()

        def set_protocol(self,p):
                self.server = p
                p.set_protocol(self)

        def dataReceived(self,data):
                self.server.transport.write(data)

        def connectionLost(self,reason):
                self.transport.loseConnection()
                self.server.transport.loseConnection()

class Clienttransfer(Protocol):
        def __init__(self):
                pass

        def set_protocol(self,p):
                self.server = p
                self.server.transport.resumeProducing()
                pass
        def dataReceived(self,data):
                self.server.transport.write(data)
                pass

factory = Factory()
factory.protocol = Transfer
reactor.listenTCP(1099,factory)
reactor.run()
寫得比較倉促紅色代碼為轉寄的目的地址以及連接埠。

小測試了下。呵呵還行 遠端桌面使用正常。我這個的實現比較惡,毫無構架擴充性而言,慢慢來 呵呵。

這個程式挺適合入門練手的,包括了服務端和用戶端的寫法,其中注意綠色標記的地方,我剛開始沒有注意這個,

導致 self.server.transport.write(data)中的server未初始化就開始寫資料。

o~了。。

寫完後看了看twisted的源碼,發現在twisted.protocols.base 下有一個portforword.py。

貼出來:
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.

"""
A simple port forwarder.
"""

# Twisted imports
from twisted.internet import protocol
from twisted.python import log

class Proxy(protocol.Protocol):
    noisy = True

    peer = None

    def setPeer(self, peer):
        self.peer = peer

    def connectionLost(self, reason):
        if self.peer is not None:
            self.peer.transport.loseConnection()
            self.peer = None
        elif self.noisy:
            log.msg("Unable to connect to peer: %s" % (reason,))

    def dataReceived(self, data):
        self.peer.transport.write(data)

class ProxyClient(Proxy):
    def connectionMade(self):
        self.peer.setPeer(self)
        # We're connected, everybody can read to their hearts content.
        self.peer.transport.resumeProducing()

class ProxyClientFactory(protocol.ClientFactory):

    protocol = ProxyClient

    def setServer(self, server):
        self.server = server

    def buildProtocol(self, *args, **kw):
        prot = protocol.ClientFactory.buildProtocol(self, *args, **kw)
        prot.setPeer(self.server)
        return prot

    def clientConnectionFailed(self, connector, reason):
        self.server.transport.loseConnection()

class ProxyServer(Proxy):

    clientProtocolFactory = ProxyClientFactory

    def connectionMade(self):
        # Don't read anything from the connecting client until we have
        # somewhere to send it to.
        self.transport.pauseProducing()

        client = self.clientProtocolFactory()
        client.setServer(self)

        from twisted.internet import reactor
        reactor.connectTCP(self.factory.host, self.factory.port, client)

class ProxyFactory(protocol.Factory):
    """Factory for port forwarder."""

    protocol = ProxyServer

    def __init__(self, host, port):
        self.host = host
        self.port = port

功能一樣,但優雅多了, 好好學習....

keep going ... 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.