3

给定以下代码:

  class sshConnection():
      def getConnection(self,IP,USN,PSW):
        try:
            client = paramiko.SSHClient()
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            client.connect(IP,username=USN, password=PSW)
            channel = client.invoke_shell()
            t = channel.makefile('wb')
            stdout = channel.makefile('rb')
            print t    //The important lines
            return t   //The important lines
        except:
            return -1

   myConnection=sshConnection().getConnection("xx.xx.xx.xx","su","123456")
   print myConnection

结果:

<paramiko.ChannelFile from <paramiko.Channel 1 (open) window=1000 ->     <paramiko.Transport at 0xfcc990L (cipher aes128-ctr, 128 bits) (active; 1 open channel(s))>>>

<paramiko.ChannelFile from <paramiko.Channel 1 (closed) -> <paramiko.Transport at 0xfcc930L (unconnected)>>>

这意味着:在类方法内部,t连接是连接的,但是在返回这个连接描述符之后,连接就丢失了。

为什么会这样,我怎样才能让它工作?

谢谢!

4

2 回答 2

1

当方法返回时,您的客户端将超出范围,这将自动关闭通道文件。尝试将客户端存储为成员,并保留 sshConnection 直到您完成客户端,就像这样;

import paramiko

class sshConnection():
    def getConnection(self,IP,USN,PSW):
      try:
          self.client = paramiko.SSHClient()
          self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
          self.client.connect(IP,username=USN, password=PSW)
          channel = self.client.invoke_shell()
          self.stdin = channel.makefile('wb')
          self.stdout = channel.makefile('rb')
          print self.stdin    # The important lines
          return 0   # The important lines
      except:
          return -1

conn = sshConnection()
print conn.getConnection("ubuntu-vm","ic","out69ets")
print conn.stdin


$ python test.py 
<paramiko.ChannelFile from <paramiko.Channel 1 (open) window=2097152 -> <paramiko.Transport at 0xb3abcd0L (cipher aes128-ctr, 128 bits) (active; 1 open channel(s))>>>
<paramiko.ChannelFile from <paramiko.Channel 1 (open) window=2097152 -> <paramiko.Transport at 0xb3abcd0L (cipher aes128-ctr, 128 bits) (active; 1 open channel(s))>>>

当然,要稍微清理一下,您可能希望隐藏 stdin/stdout 并通过 sshConnection 上的其他方法使用它们,这样您只需跟踪它而不是多个文件一个连接。

于 2013-06-26T10:24:24.033 回答
0

您必须在某处返回并存储clientandchannel变量。它们应该与生命一样长t,但显然 paramiko 不遵守 Python 约定。

于 2013-06-26T10:25:29.737 回答