Search code examples
pythonpython-3.xsshparamiko

Paramiko exec_command fails with 'NoneType' object is not iterable


I'm new to Paramiko. I am attempting to create a simple script that allows anyone to use their Linux credentials to run the command. I decided to test with a simple ls command but I am receiving errors.

import paramiko
username = *<USERNAME>*
hostname = *<HOSTNAME>*
port = 22
trans = paramiko.Transport((hostname,port))
trans.connect(username=username, password=password)
channel = trans.open_channel("session")
print(channel.send_ready())
print(channel.get_transport())
stdin,stdout,stderr = channel.exec_command("ls -lah")
trans.close()

I am receiving the following error:

TypeError                                 Traceback (most recent call last)
<ipython-input-28-ce837beea6fe> in <module>()
      6 trans.connect(username=username, password=password)
      7 channel = trans.open_channel("session")
----> 8 stdin,stdout,stderr = channel.exec_command("ls -lah")

TypeError: 'NoneType' object is not iterable

Any Ideas as to what I might be doing incorrectly?


Solution

    1. There's no session channel in SSH (unless your server has some non-standard channels implemented). There are sftp, shell and exec channels.

      You want to use exec channel.

    2. And you do not need to open exec channel explicitly in Paramiko. Just use SSHClient.exec_command method.

      SSHClient.exec_command (contrary to Channel.exec_command) returns 3-touple.

    See for example Python Paramiko - Run command:

    s = paramiko.SSHClient()
    s.load_system_host_keys()
    s.connect(hostname, port, username, password)
    command = 'ls -lah'
    (stdin, stdout, stderr) = s.exec_command(command)