2012-06-19 39 views
3

我一直在使用插座蟒蛇聊天客戶端,我想通過SSH服務器連接到聊天服務器,我看到的paramiko我怎樣才能通過ssh隧道連接到服務器在python

import paramiko 
ssh = paramiko.SSHClient() 

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 

ssh.connect('<hostname>', username='<username>', password='<password>', key_filename='<path/to/openssh-private-key-file>') 

stdin, stdout, stderr = ssh.exec_command('ls') 
print stdout.readlines() 
ssh.close() 

但我cannt搞清楚如何鏈接這與我這樣的插座連接

from twisted.internet.protocol import ClientFactory 
from twisted.protocols.basic import LineReceiver 
from twisted.internet import reactor 
import sys 

class EchoClient(LineReceiver): 
    end="Bye-bye!" 
    def connectionMade(self): 
     self.sendLine("Hello, world!") 
     self.sendLine("What a fine day it is.") 
     self.sendLine(self.end) 

    def lineReceived(self, line): 
     print "receive:", line 
     if line==self.end: 
      self.transport.loseConnection() 

class EchoClientFactory(ClientFactory): 
    protocol = EchoClient 

    def clientConnectionFailed(self, connector, reason): 
     print 'connection failed:', reason.getErrorMessage() 
     reactor.stop() 

    def clientConnectionLost(self, connector, reason): 
     print 'connection lost:', reason.getErrorMessage() 
     reactor.stop() 

def main(): 
    factory = EchoClientFactory() 
    reactor.connectTCP('localhost', 8000, factory) 
    reactor.run() 

if __name__ == '__main__': 
    main() 

所以我怎樣才能連接到服務器通過在Python中的SSH隧道?

+0

在cmdline上創建ssh隧道,然後portforward並連接到本地端監聽端口 –

+0

不能通過python本身轉發它嗎? –

回答

1

你總是可以使用Twisted Conch,他們有examples實現簡單的SSH客戶端/服務器可能是有用的。

1

您可以在SSHClient上使用invoke_shell()方法,它會返回類似socket的對象(通道),因此您可以像在shell中那樣創建新的ssh通道。所有以下連接可通過此通道訪問。