How can I simply SSH to a remote server from a local Python (3.0) script, supply a login/password, execute a command and print the output to the Python console?
I would rather not use any large external library or install anything on the remote server.
I have written Python bindings for libssh2. Libssh2 is a client-side library implementing the SSH2 protocol.
I found paramiko to be a bit too low-level, and Fabric not especially well-suited to being used as a library, so I put together my own library called spur that uses paramiko to implement a slightly nicer interface:
You can also choose to print the output of the program as it's running, which is useful if you want to see the output of long-running commands before it exits:
Your definition of "simplest" is important here - simple code means using a module (though "large external library" is an exaggeration).
I believe the most up-to-date (actively developed) module is paramiko. It comes with demo scripts in the download, and has detailed online API documentation. You could also try PxSSH, which is contained in pexpect. There's a short sample along with the documentation at the first link.
Again with respect to simplicity, note that good error-detection is always going to make your code look more complex, but you should be able to reuse a lot of code from the sample scripts then forget about it.
If you want to avoid any extra modules, you can use the subprocess module to run
and capture the output.
Try something like:
To deal with usernames and passwords, you can use subprocess to interact with the ssh process, or you could install a public key on the server to avoid the password prompt.
Have a look at spurplus, a wrapper around spur and paramiko that we developed to manage remote machines and perform file operations.
Spurplus provides a
check_output()
function out-of-the-box:For benefit of those who reach here googling for python ssh sample. The original question and answer are almost a decode old now. It seems that the paramiko has gain a bit of functionalities (Ok. I'll admit - pure guessing here - I'm new to Python) and you can create ssh client directly with paramiko.
This code was adapted from demo of https://github.com/paramiko/paramiko It works for me.