1

Strange behaviour in Python & paramiko 1.7.7.1.

I have a function and a class that have effectively exactly the same code but the class breaks it across 2 methods. The behaviour of the paramiko library is different.

The function: opens an ssh connection, runs a command, waits for completion and gets the exit value.

The class: in setup() opens an ssh connection, runs a command and in finish() waits for completion and gets the exit value.

I note that if I read from stdout in setup() it then works (commented out).

I'm interested in two things,

  1. how to get the class to work while storing the channel as a member, and

  2. what exactly is different in terms of assignments etc. that is changing the behaviour?

Output:

[function]
exitVal: 0
stdout: hello

[class]
exitVal: -1
stdout: 

Code:

MY_SERVER is a hostname with key-based login (no password required).

from paramiko import SSHClient

SSH_SERVER = "MY_SERVER"
SSH_CMD = "echo 'hello'"

def working_function():

    client = SSHClient()
    client.load_system_host_keys()

    # connect with current user credentials
    client.connect(SSH_SERVER)

    sshChannel = client.get_transport().open_session()

    sshChannel.exec_command(SSH_CMD)
    stdout = sshChannel.makefile('rb')
    exitVal = sshChannel.recv_exit_status()

    print "exitVal: {0}\nstdout: {1}\n".format(exitVal, stdout.read())

class NotWorkingClass:

    def setup(self):

        client = SSHClient()
        client.load_system_host_keys()

        # connect with current user credentials
        client.connect(SSH_SERVER)

        self.sshChannel = client.get_transport().open_session()
        self.sshChannel.exec_command(SSH_CMD)

        self.stdout = self.sshChannel.makefile('rb')

        # works
        # self.stdout.read()

    def finish(self):

        exitVal = self.sshChannel.recv_exit_status()
        print "exitVal: {0}\nstdout: {1}\n".format(exitVal, self.stdout.read())

working_function()

c = NotWorkingClass()
c.setup()
c.finish()
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
flend
  • 411
  • 1
  • 4
  • 10

0 Answers0