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

client変数と変数を返してどこかに保存する必要がありchannelます。命ある限り生かしておくべきなtのですが、どうやらparamikoはPythonの慣例に従わないようです。

于 2013-06-26T10:25:29.737 に答える