2013-06-26 42 views
3

考虑下面的代码: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连接点连接,但回国后这个连接描述符,连接丢失。

这是为什么,我该如何使它工作?

谢谢!

回答

0

您必须返回并存储某处clientchannel变量。只要t生活,他们应该保持活着,但显然paramiko不遵守Python约定。

+0

谢谢,那是我不知道的。 – user2162550

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

当然,清理了一点东西,你可能希望隐藏标准输入/输出并通过sshConnection其他方法用它们来代替,这样你就只需要保留的,与其多个轨道文件一个连接。

+0

谢谢!有用。 – user2162550

相关问题