Search code examples
pythonsshparamikoswitching

Executing command using Paramiko exec_command on device is not working


I am trying to use Paramiko to SSH into a Brocade switch and carry out remote commands. The code is as given below:

def ssh_connector(ip, userName, passWord, command):
 ssh = paramiko.SSHClient()
 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
 ssh.connect(ip, username=userName, password=passWord, port=22)
 stdin, stdout, stderr = ssh.exec_command(command)
 print stdout.readlines()

ssh_connector(ip, userName, passWord, 'show running-config')

While trying to run the code, I encounter a strange error which is as given below.

Protocol error, doesn't start with scp!

I do not know the cause of the error or whether the SSH connection was successful. Could you please help me with this?


Solution

  • If the SSHClient.exec_command does not work, the first thing to test is to try (on one line):

    ssh user@host command
    

    That will use the same SSH API (the "exec" channel) as SSHClient.exec_command. If you are on Windows, you can use plink (from PuTTY packages) instead of ssh. If ssh/plink fails too, it indicates that your device does not support the SSH "exec" channel.


    In your case, it seems that the "exec" channel on Brocade SSH server is implemented to support the scp command only.

    As you claim to be able to "SSH" to the switch, it seems that the "shell" channel is fully working.

    While it is generally not recommended to use the "shell" channel for command automation, with your server you won't have other option. Use the SSHClient.invoke_shell and write the commands to the channel (= to the shell) using the Channel.send.

    channel = ssh.invoke_shell()
    channel.send('ls\n')
    channel.send('exit\n')
    

    See also What is the difference between exec_command and send with invoke_shell() on Paramiko?

    A similar question on C#/SSH.NET: SSH.NET is not executing command on device.


    Obligatory warning: Do not use AutoAddPolicy – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".