3

ソケットを使用する Python チャット クライアントがあります。ssh サーバー経由でチャット サーバーに接続したいのですが、paramiko を見ました。

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()

しかし、これをこのようなソケット接続にリンクする方法がわかりません

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トンネルを介してサーバーに接続するにはどうすればよいですか?

4

2 に答える 2

1

Twisted Conchはいつでも使用でき、使用できるシンプルな SSH クライアント/サーバーの実装があります。

于 2012-06-19T13:25:29.717 に答える
1

SSHClient で invoke_shell() メソッドを使用すると、ソケットのようなオブジェクト (チャネル) が返されるため、シェルで行うのと同じ方法で新しい ssh トンネルを作成できます。以降のすべての接続には、このチャネルからアクセスできます。

于 2012-06-19T13:51:24.607 に答える