使用Paramiko执行exec_command报错:Unknown command: `ls',求助
ls" in Paramiko SSH Command Execution Let’s break down why this error is happening and how to fix it—this is a common quirk of non-interactive SSH sessions in Paramiko.
Common Reasons & Fixes
1. Use the Absolute Path for ls
The most likely issue is that the ls executable isn’t in the minimal PATH environment that Paramiko uses when running exec_command (since it doesn’t spin up a full interactive shell).
First, manually SSH into your remote host and run which ls to get the absolute path (it’s usually /bin/ls or /usr/bin/ls). Then update your command:
my_cmd = "/bin/ls -ltr"
2. Run the Command Inside a Shell
If the path fix doesn’t work, force the command to run within a shell like bash—this loads the full user environment (including your normal PATH settings from .bashrc or .profile):
my_cmd = "bash -c 'ls -ltr'"
3. Check if the Remote Host is Unix-like
Wait—could the remote host be Windows? If it’s running an SSH server (like OpenSSH for Windows), ls isn’t a native command. You’ll need to use dir instead:
my_cmd = "dir"
Why This Happens
When you use chan.exec_command(cmd) in Paramiko, it runs the command directly without launching a full interactive terminal session. That means it doesn’t inherit all the environment variables you get when you SSH manually. So even if ls works perfectly in a regular SSH window, it might not be found in the stripped-down environment used by exec_command.
Test the Solution
Swap out your my_cmd with one of the options above and re-run your function. If it outputs the directory listing as expected, you’ve nailed the problem.
内容的提问来源于stack exchange,提问作者May

