2013-06-26 44 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

相關問題