Skip to content

Cannot return channel or file-like object from a function, will close connection!! #440

Open

Description

@lwcolton

For some reason I cannot return a file-like object or a channel from inside of a function. Doing so causes the channel to be immediately closed.

Example:

import paramiko

def testp():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(
        paramiko.AutoAddPolicy())
    ssh.connect("testserver")
    stdin, stdout, stderr = ssh.exec_command("sleep 5; echo works")
    return stdout

stdout = testp()
print("From function:")
print(repr(stdout))
print(stdout.read())
print("\n")

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(
    paramiko.AutoAddPolicy())
ssh.connect("testserver")
stdin, stdout, stderr = ssh.exec_command("sleep 5; echo works")
print(repr(stdout))
print(stdout.read())
print("\n")

Output:

$ python testp.py
From function:
<paramiko.ChannelFile from <paramiko.Channel 1 (closed) -> <paramiko.Transport at 0xc187e240 (unconnected)>>>
b''


<paramiko.ChannelFile from <paramiko.Channel 1 (open) window=2097152 -> <paramiko.Transport at 0xc187e208 (cipher aes128-ctr, 128 bits) (active; 1 open channel(s))>>>
b'works\n'

Version info:

$ python
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import paramiko
>>> paramiko.__version__
'1.15.1'

$ cat /etc/*release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=14.04
DISTRIB_CODENAME=trusty
DISTRIB_DESCRIPTION="Ubuntu 14.04.1 LTS"

Activity

  1. pkittenis commented on Dec 17, 2014

    @pkittenis

    Need to return the SSHClient object or it goes out of scope:

    
    def testp():
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(
            paramiko.AutoAddPolicy())
        ssh.connect("tesstserver")
        stdin, stdout, stderr = ssh.exec_command("sleep 5; echo works")
        return ssh, stdout
    
    ssh, stdout = testp()
    print("From function:")
    print(repr(stdout))
    print(stdout.read())
    print("\n")
    

    Output

    In [37]: ssh, stdout = testp()
    
    In [38]: print("From function:")
    From function:
    
    In [39]: print(repr(stdout))
    <paramiko.ChannelFile from <paramiko.Channel 1 (open) window=2097152 -> <paramiko.Transport at 0xf4042d50L (cipher aes128-ctr, 128 bits) (active; 1 open channel(s))>>>
    
    In [40]: print(stdout.read())
    works
    
    
    In [41]: print("\n")
    
  2. ghanshyamgaurav commented on Sep 5, 2017

    @ghanshyamgaurav

    You can do this by this way too.

    ## Example:
    import paramiko

    def testp():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(
    paramiko.AutoAddPolicy())
    ssh.connect("tesstserver")
    return ssh

    ssh = testp()
    stdout=ssh.exec_command("sleep 5; echo works")[1]
    print("From function:")
    print(repr(stdout))
    print(stdout.read())
    print("\n")

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(
    paramiko.AutoAddPolicy())
    ssh.connect("tesstserver")
    stdin, stdout, stderr = ssh.exec_command("sleep 5; echo works")
    print(repr(stdout))
    print(stdout.read())
    print("\n")

    ## Output:
    From function:
    <paramiko.ChannelFile from <paramiko.Channel 0 (open) window=2097152 -> <paramiko.Transport at 0x374b330L (cipher aes128-ctr, 128 bits) (active; 1 open channel(s))>>>
    works

    <paramiko.ChannelFile from <paramiko.Channel 0 (open) window=2097152 -> <paramiko.Transport at 0x374b270L (cipher aes128-ctr, 128 bits) (active; 1 open channel(s))>>>
    works

  3. ploxiln commented on Sep 5, 2017

    @ploxiln
    Contributor

    This issue can be closed now, because this was fixed in a not-so-great way in #891 and then fixed somewhat more properly in #952

  4. smolrise commented on Jun 11, 2021

    @smolrise

    I using paramiko-2.1.1 and this bug still in place. This bug makes paramiko library absolutely unusable because if I return from any method Channel, it returned closed. If I return SSHClient, and then use invoke_shell() to get the channel it establish a new connection.

  5. ploxiln commented on Jun 11, 2021

    @ploxiln
    Contributor

    The fixes are present in paramiko-2.1.3, released in June 2017. Your version is even older.

  6. smolrise commented on Jun 17, 2021

    @smolrise

    Thanks a lot! You are right. I have installed v2.1.6 and it really works correctly. But in RedHat repository last official version is 2.1.1, and using pip is prohibited in our environment. The Internet is also unavailable. Is there any ways how to make new version installed from tar.gz archive without pip?
    P.S.: we have python2 available only

  7. ploxiln commented on Jun 17, 2021

    @ploxiln
    Contributor

    you can untar the archive, then run python setup.py install

    (you'll have to figure out any additional details on your own, sorry)

  8. smolrise commented on Jun 17, 2021

    @smolrise

    I already tried it, but there were a lot of errors. But anyway thanks a lot. I will try to check some dependencies, it this could be the reason for the failure of the installation last time.

  9. gajendraks commented on Jul 27, 2021

    @gajendraks

    If we return all the three channels(stdin, stdout, stderr) from the function, no connection will get closed.

  10. Amonimus commented on May 6, 2026

    @Amonimus

    Tested on both 3.0.0 and 4.0.0
    Compare:

    1.

    import paramiko
    from paramiko.client import SSHClient
    
    def run_command(ssh: SSHClient):
    	i, o, e = ssh.exec_command("show running-config", get_pty=False)
    	return i, o
    
    def get_config(ip: str):
    	print(ip)
    	ssh: SSHClient = SSHClient()
    	ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    	ssh.connect(ip, username='U', password='P')
    	i, o = run_command(ssh)
    	print("OUTPUT", o.read().decode())
    	ssh.close()
    
    if __name__ == '__main__':
    	get_config('X.X.X.X')

    2.

    import paramiko
    from paramiko.client import SSHClient
    
    def run_command(ssh: SSHClient):
    	i, o, e = ssh.exec_command("show running-config", get_pty=False)
    	return o
    
    def get_config(ip: str):
    	print(ip)
    	ssh: SSHClient = SSHClient()
    	ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    	ssh.connect(ip, username='U', password='P')
    	o = run_command(ssh)
    	print("OUTPUT", o.read().decode())
    	ssh.close()
    
    if __name__ == '__main__':
    	get_config('X.X.X.X')

    1 works fine, 2 stops early and gives me an empty stdout. The only difference is a single variable not being returned from a local function.

    From what I see, if either of ChannelFile are not returned, it gets unreferenced, which automatically calls BufferedFile.del() and apparently closes the entire channel, despite me neither telling it to nor the client session being over yet (the same happens if SSHClient is run through context manager).

    Since this related report has been here for over a decade, I suppose it's intentional, but I feel tossing an unwanted variable around until you're done with the session is not intuitive or logical. Neither the exec_command's docstring nor docs mention that this is a behavior to keep in mind, and I've spent a day wondering if I'm having a stroke. From what I understand, closing input in SSH is equivalent to asking to close the session, but I don't see why the input is closed preemptively.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions