【问题标题】:How can i connect to server through ssh tunnel in python如何通过 python 中的 ssh 隧道连接到服务器
【发布时间】:2012-06-21 13:03:07
【问题描述】:

我有一个使用套接字的 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 隧道连接到服务器?

【问题讨论】:

  • 在 cmdline 上创建 ssh 隧道,然后 portforward 并连接到本地监听端口
  • 不能通过python本身转发吗?

标签: python sockets ssh


【解决方案1】:

您总是可以使用Twisted Conch,他们有examples 来实现可能有用的简单 SSH 客户端/服务器。

【讨论】:

    【解决方案2】:

    您可以在 SSHClient 上使用 invoke_shell() 方法,它返回类似套接字的对象(通道),因此您可以像在 shell 中一样创建新的 ssh 隧道。并且后面的所有连接都可以通过这个通道访问。

    【讨论】:

      猜你喜欢
      • 2020-09-30
      • 2019-11-12
      • 1970-01-01
      • 2018-02-19
      • 2011-04-08
      • 2017-01-01
      • 2020-07-05
      • 2019-08-01
      • 2014-03-21
      相关资源
      最近更新 更多