Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

paramiko.SSHException: Channel closed #1444

Open
plegrand1 opened this issue May 15, 2019 · 14 comments
Open

paramiko.SSHException: Channel closed #1444

plegrand1 opened this issue May 15, 2019 · 14 comments
Labels

Comments

@plegrand1
Copy link

plegrand1 commented May 15, 2019

I am a complete beginner with paramiko and I am trying to run a command on an Alcatel OS6450 switch.

I can make ssh with rsa key (no password) without problem on this switch

ssh admin@192.168.1.1 
  
Welcome to the Alcatel-Lucent OmniSwitch 6450
Software Version 6.6.5.63.R02 GA, December 16, 2014. 

Copyright(c), 1994-2014 Alcatel-Lucent. All Rights reserved.

OmniSwitch(TM) is a trademark of Alcatel-Lucent registered
in the United States Patent and Trademark Office.
  
SW001-> dir

Listing Directory /flash:

-rw       310 Mar  1  2000 boot.params 
drw      2048 Sep  3  2002 certified/
drw      2048 Sep  3  2002 working/
-rw     64000 May  7 10:20 swlog1.log 
-rw     64000 May 21  2000 swlog2.log 
-rw        12 Jan  1  2001 boot.slot.cfg 
drw      2048 Jan  1  2001 switch/
drw      2048 Jan  1  2001 network/
-rw        20 Jan  1  2001 installed 

	55750656 bytes free

SW001-> exit
Connection to 192.168.1.1 closed.

I can't run directly a command from ssh

ssh admin@192.168.1.1 dir
exec request failed on channel 0

Then i made a try with paramiko with some scripts found on the net, all give me the same error :

import paramiko
k = paramiko.RSAKey.from_private_key_file("/home/pascal/.ssh/id_rsa")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print "connecting"
c.connect( hostname = "192.168.1.1", username = "admin", pkey = k )
print "connected"
commands = [ "show spantree ports blocking" ]
for command in commands:
	print "Executing {}".format( command )
	stdin , stdout, stderr = c.exec_command(command)
	print stdout.read()
	print( "Errors")
	print stderr.read()
c.close()


This script give me this message :

connecting
connected
Executing show spantree ports blocking
Traceback (most recent call last):
  File "test.py", line 11, in <module>
    stdin , stdout, stderr = c.exec_command(command)
  File "/usr/lib/python2.7/dist-packages/paramiko/client.py", line 499, in exec_command
    chan.exec_command(command)
  File "/usr/lib/python2.7/dist-packages/paramiko/channel.py", line 72, in _check
    return func(self, *args, **kwds)
  File "/usr/lib/python2.7/dist-packages/paramiko/channel.py", line 257, in exec_command
    self._wait_for_event()
  File "/usr/lib/python2.7/dist-packages/paramiko/channel.py", line 1208, in _wait_for_event
    raise e
paramiko.ssh_exception.SSHException: Channel closed.

Is there a solution ?
Thanks for your help

@MrMino
Copy link
Contributor

MrMino commented May 15, 2019

Hi

In order for SSHConnection.exec_command() to work, an SSH server has to support exec_command channels, and not every server does. In this case, the server probably rejects the request to open the channel of this type, hence for paramiko it looks like the Channel is closed.

To my knowledge, the only way to interact with such servers is to use invoke_shell().

Most ssh servers running on network switches won't have the feature implemented. That's also the reason behind ssh user@host command not working

@gksalil
Copy link

gksalil commented Feb 16, 2020

I am trying to do some sftp operation with paramiko and while doing so I am getting same error. Below is my code, what could be the reason ?

1 import paramiko
2 paramiko.util.log_to_file(".paramiko.log")
3
4 # Open a transport
5 host,port = "10.50.156.102",22
6 transport = paramiko.Transport((host,port))
7
8 # Auth
9 username,password = "root","x"
10 transport.connect(None,username,password)
11
12 # Go!
13 print transport
14 sftp = paramiko.SFTPClient.from_transport(transport)
15
16 # Download
17 filepath = "/etc/passwd"
18 localpath = "/tmp/remotepasswd"
19 sftp.get(filepath,localpath)
20
21 # Close
22 if sftp: sftp.close()
23 if transport: transport.close()

python mytest.py

<paramiko.Transport at 0xa9cbb8d0L (cipher aes128-ctr, 128 bits) (active; 0 open channel(s))>
Traceback (most recent call last):
File "mytest.py", line 16, in
sftp = paramiko.SFTPClient.from_transport(transport)
File "/home/sagk/dev/paramiko/paramiko/sftp_client.py", line 169, in from_transport
chan.invoke_subsystem("sftp")
File "/home/sagk/dev/paramiko/paramiko/channel.py", line 72, in _check
return func(self, *args, **kwds)
File "/home/sagk/dev/paramiko/paramiko/channel.py", line 283, in invoke_subsystem
self._wait_for_event()
File "/home/sagk/dev/paramiko/paramiko/channel.py", line 1226, in _wait_for_event
raise e
paramiko.ssh_exception.SSHException: Channel closed.

@FlorianHeigl
Copy link

@gksalil i am having the same problem in front of me. it is related to the sftp server on the Omniswitch. It seems to be disabled. Some blog posts indicated one should do scp-sftp to enable it, but that command does not exist.

Since it's your own code, I hope you can find a good workaround.
The problem is, in any case, the switch.

@bpottier
Copy link

I've been dealing with intermittent channel closed failures. I regularly transfers multiple files per day (to the same server) but every now and again the process fails with the following error:

 File "/home/file-transfers/lib/python3.9/site-packages/paramiko/sftp_client.py", line 169, in from_transport
   chan.invoke_subsystem("sftp")
 File "/home/file-transfers/lib/python3.9/site-packages/paramiko/channel.py", line 72, in _check
   return func(self, *args, **kwds)
 File "/home/file-transfers/lib/python3.9/site-packages/paramiko/channel.py", line 283, in invoke_subsystem
   self._wait_for_event()
 File "/home/file-transfers/lib/python3.9/site-packages/paramiko/channel.py", line 1226, in _wait_for_event
   raise e
paramiko.ssh_exception.SSHException: Channel closed.

Any idea what might be going on? Unfortunately, I have no view of anything happening on the server as it is out of my control.

@gamesharkmike
Copy link

I get channel closed when I try to use ssh.exec_command(x)

It seems I'm not the only one from my research so far https://www.reddit.com/r/learnpython/comments/mz30w6/issue_with_paramikos_invoke_shell_not_executing/

Is it possible to get the output of a command using paramiko?

@jun66j5
Copy link
Contributor

jun66j5 commented Nov 20, 2022

Please post your code and the traceback. At least, exec_command() woks fine on my environment. Also invoke_shell() shouldn't be used unless you want control shell via pty.

@bskinn bskinn added the Support label Nov 25, 2022
@karandemyst
Copy link

karandemyst commented Jan 29, 2023

I'm having the similar issue, not sure about the reason behind dragging this issue for more than a year. Hoping for the solution. Thanks & regards.

CODE-BLOCK:
`import paramiko
paramiko.util.log_to_file(".paramiko.log")

ssh = paramiko.SSHClient()

ssh.load_system_host_keys()
print('Host keys loaded!')

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print('Set missing host keys done!')

the_key = paramiko.RSAKey.from_private_key_file('<RSA_key_file.key>')
print('Key has been fetched!')

print('Connecting . . .')

ssh.connect('',port=22,username='', pkey=the_key)

print('Connected . . .')

stdin, stdout, stderr = ssh.exec_command('ls -l')
`

ERROR:
host keys loaded! sett missing host keys done! key has been fetched! Connecting . . . Connected . . . Traceback (most recent call last): File "test_sftp_putty.py", line 20, in <module> stdin, stdout, stderr = ssh.exec_command('ls -l') File "/Users/karan/Desktop/nationwide/workflow/.venv/lib/python3.7/site-packages/paramiko/client.py", line 531, in exec_command chan.exec_command(command) File "/Users/karan/Desktop/nationwide/workflow/.venv/lib/python3.7/site-packages/paramiko/channel.py", line 72, in _check return func(self, *args, **kwds) File "/Users/karan/Desktop/nationwide/workflow/.venv/lib/python3.7/site-packages/paramiko/channel.py", line 257, in exec_command self._wait_for_event() File "/Users/karan/Desktop/nationwide/workflow/.venv/lib/python3.7/site-packages/paramiko/channel.py", line 1226, in _wait_for_event raise e paramiko.ssh_exception.SSHException: Channel closed.

@jun66j5
Copy link
Contributor

jun66j5 commented Jan 31, 2023

Hi @karandemyst

paramiko.util.log_to_file(".paramiko.log")

It appears you are using logging. Please provide .paramiko.log file when the issue occurred. Also, what kind and version of the remote server you are connecting? What version of paramiko you are using?

@fhamborg
Copy link

fhamborg commented May 5, 2023

I'm getting the same error and this is my paramiko log (using 3.1.0 on python 3.10)

DEBUG:paramiko.transport:starting thread (client mode): 0x2b46acb0
DEBUG:paramiko.transport:Local version/idstring: SSH-2.0-paramiko_3.1.0
DEBUG:paramiko.transport:Remote version/idstring: SSH-2.0-OpenSSH_8.9p1 Ubuntu-3ubuntu0.1
INFO:paramiko.transport:Connected (version 2.0, client OpenSSH_8.9p1)
DEBUG:paramiko.transport:=== Key exchange possibilities ===
DEBUG:paramiko.transport:kex algos: curve25519-sha256, curve25519-sha256@libssh.org, ecdh-sha2-nistp256, ecdh-sha2-nistp384, ecdh-sha2-nistp521, sntrup761x25519-sha512@openssh.com, diffie-hellman-group-exchange-sha256, diffie-hellman-group16-sha512, diffie-hellman-group18-sha512, diffie-hellman-group14-sha256
DEBUG:paramiko.transport:server key: rsa-sha2-512, rsa-sha2-256, ecdsa-sha2-nistp256, ssh-ed25519
DEBUG:paramiko.transport:client encrypt: chacha20-poly1305@openssh.com, aes128-ctr, aes192-ctr, aes256-ctr, aes128-gcm@openssh.com, aes256-gcm@openssh.com
DEBUG:paramiko.transport:server encrypt: chacha20-poly1305@openssh.com, aes128-ctr, aes192-ctr, aes256-ctr, aes128-gcm@openssh.com, aes256-gcm@openssh.com
DEBUG:paramiko.transport:client mac: umac-64-etm@openssh.com, umac-128-etm@openssh.com, hmac-sha2-256-etm@openssh.com, hmac-sha2-512-etm@openssh.com, hmac-sha1-etm@openssh.com, umac-64@openssh.com, umac-128@openssh.com, hmac-sha2-256, hmac-sha2-512, hmac-sha1
DEBUG:paramiko.transport:server mac: umac-64-etm@openssh.com, umac-128-etm@openssh.com, hmac-sha2-256-etm@openssh.com, hmac-sha2-512-etm@openssh.com, hmac-sha1-etm@openssh.com, umac-64@openssh.com, umac-128@openssh.com, hmac-sha2-256, hmac-sha2-512, hmac-sha1
DEBUG:paramiko.transport:client compress: none, zlib@openssh.com
DEBUG:paramiko.transport:server compress: none, zlib@openssh.com
DEBUG:paramiko.transport:client lang: <none>
DEBUG:paramiko.transport:server lang: <none>
DEBUG:paramiko.transport:kex follows: False
DEBUG:paramiko.transport:=== Key exchange agreements ===
DEBUG:paramiko.transport:Kex: curve25519-sha256@libssh.org
DEBUG:paramiko.transport:HostKey: ssh-ed25519
DEBUG:paramiko.transport:Cipher: aes128-ctr
DEBUG:paramiko.transport:MAC: hmac-sha2-256
DEBUG:paramiko.transport:Compression: none
DEBUG:paramiko.transport:=== End of kex handshake ===
DEBUG:paramiko.transport:kex engine KexCurve25519 specified hash_algo <built-in function openssl_sha256>
DEBUG:paramiko.transport:Switch to new keys ...
DEBUG:paramiko.transport:Adding ssh-ed25519 host key for [94.16.106.77]:2222: b'70f5d90a3dbcbf6dbcb68f4cfa247c0d'
DEBUG:paramiko.transport:Got EXT_INFO: {'server-sig-algs': b'ssh-ed25519,sk-ssh-ed25519@openssh.com,ssh-rsa,rsa-sha2-256,rsa-sha2-512,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,sk-ecdsa-sha2-nistp256@openssh.com,webauthn-sk-ecdsa-sha2-nistp256@openssh.com', 'publickey-hostbound@openssh.com': b'0'}
DEBUG:paramiko.transport:Trying discovered key b'24df29055e21aef8b1160b70c7ce8269' in /Users/felix/.ssh/id_rsa
DEBUG:paramiko.transport:userauth is OK
DEBUG:paramiko.transport:Finalizing pubkey algorithm for key of type 'ssh-rsa'
DEBUG:paramiko.transport:Our pubkey algorithm list: ['rsa-sha2-512', 'rsa-sha2-256', 'ssh-rsa']
DEBUG:paramiko.transport:Server-side algorithm list: ['ssh-ed25519', 'sk-ssh-ed25519@openssh.com', 'ssh-rsa', 'rsa-sha2-256', 'rsa-sha2-512', 'ssh-dss', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', 'ecdsa-sha2-nistp521', 'sk-ecdsa-sha2-nistp256@openssh.com', 'webauthn-sk-ecdsa-sha2-nistp256@openssh.com']
DEBUG:paramiko.transport:Agreed upon 'rsa-sha2-512' pubkey algorithm
INFO:paramiko.transport:Authentication (publickey) successful!
DEBUG:paramiko.transport:[chan 0] Max packet in: 32768 bytes
DEBUG:paramiko.transport:Received global request "hostkeys-00@openssh.com"
DEBUG:paramiko.transport:Rejecting "hostkeys-00@openssh.com" global request from server.
DEBUG:paramiko.transport:Debug msg: b'/home/felix/.ssh/authorized_keys:1: key options: agent-forwarding port-forwarding pty user-rc x11-forwarding'
DEBUG:paramiko.transport:[chan 0] Max packet out: 32768 bytes
DEBUG:paramiko.transport:Secsh channel 0 opened.
DEBUG:paramiko.transport:[chan 0] Sesch channel 0 request ok
DEBUG:paramiko.transport:[chan 0] Sesch channel 0 request ok
DEBUG:paramiko.transport:[chan 0] EOF sent (0)

@jun66j5
Copy link
Contributor

jun66j5 commented May 5, 2023

I'm getting the same error and this is my paramiko log (using 3.1.0 on python 3.10)

What the same? The same error always doesn't mean the same issue. Provide your script.

@fhamborg
Copy link

fhamborg commented May 5, 2023

thanks for the quick reply :) heres my script

class SSH:
    def __init__(self, hostname, username, port, key_filename):
        # Create an SSH client and connect to the remote server
        self.client = paramiko.SSHClient()
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.client.connect(
            hostname=hostname, username=username, key_filename=key_filename, port=port
        )
        # Open a new SSH session
        #self.channel = self.client.get_transport().open_session() # it doesn't matter, both fail
        self.channel = self.client.invoke_shell()

    def cmd(self, cmd: str):
        # Execute the bash command on the remote server and retrieve its stdout
        logger.trace(cmd)

        # Execute the command
        self.channel.exec_command(cmd)

@jun66j5
Copy link
Contributor

jun66j5 commented May 5, 2023

Your script is wrong. The channel is closed after handling exec request.

         # Execute the command
-        self.channel.exec_command(cmd)
+        self.client.exec_command(cmd)

@adityagaurav28
Copy link

I am also facing a similar error.
Here is my code:
`import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname="hostname", port='port', username='username', password='password', timeout=120)

command = "ls -l"
stdin, stdout, stderr = client.exec_command(command)
print(stdout.read())

client.close()
`

Here is the output:
Traceback (most recent call last):
File "/Users/adityagaurav/Desktop/Programming/Freelancing/Warehouse Distribution/connectSFTP.py", line 24, in
stdin, stdout, stderr = client.exec_command(command)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/adityagaurav/Desktop/Programming/Freelancing/Warehouse Distribution/env/lib/python3.11/site-packages/paramiko/client.py", line 566, in exec_command
chan.exec_command(command)
File "/Users/adityagaurav/Desktop/Programming/Freelancing/Warehouse Distribution/env/lib/python3.11/site-packages/paramiko/channel.py", line 70, in _check
return func(self, *args, **kwds)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/adityagaurav/Desktop/Programming/Freelancing/Warehouse Distribution/env/lib/python3.11/site-packages/paramiko/channel.py", line 255, in exec_command
self._wait_for_event()
File "/Users/adityagaurav/Desktop/Programming/Freelancing/Warehouse Distribution/env/lib/python3.11/site-packages/paramiko/channel.py", line 1224, in _wait_for_event
raise e
paramiko.ssh_exception.SSHException: Channel closed.

@jun66j5
Copy link
Contributor

jun66j5 commented Jul 18, 2023

@adityagaurav28

I am also facing a similar error.

Your remote server probably doesn't support exec request.

Confirm ssh username@hostname command works with your remote server using OpenSSH client, first. The exception raises if your remote server doesn't support exec request.

If the ssh command works, please provide log using paramiko.util.log_to_file(LOGFILE) and SSHClinet.get_transport().set_hexdump(True) after connecting the remote server.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests