Python类和ssh连接不能很好地工作

时间:2013-06-26 09:43:47

标签: python ssh

给出以下代码:

  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连接已连接,但在返回此连接描述符后,连接将丢失。

为什么会这样,我怎样才能使它发挥作用?

谢谢!

2 个答案:

答案 0 :(得分: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上的其他方法使用它们,这样你只需要跟踪它而不是多个文件连接。

答案 1 :(得分:0)

您必须返回并存储clientchannel变量的某个位置。只要t存在,它们就应该保持活着,但显然paramiko不遵守Python惯例。