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.
I haven't tried it, but this pysftp module might help, which in turn uses paramiko. I believe everything is client-side.
The interesting command is probably .execute() which executes an arbitrary command on the remote machine. (The module also features .get() and .put methods which allude more to its FTP character).
UPDATE:
I've re-written the answer after the blog post I originally linked to is not available anymore. Some of the comments that refer to the old version of this answer will now look weird.
You can code it yourself using Paramiko, as suggested above. Alternatively, you can look into Fabric, a python application for doing all the things you asked about:
Fabric is a Python library and
command-line tool designed to
streamline deploying applications or
performing system administration tasks
via the SSH protocol. It provides
tools for running arbitrary shell
commands (either as a normal login
user, or via sudo), uploading and
downloading files, and so forth.
I think this fits your needs. It is also not a large library and requires no server installation, although it does have dependencies on paramiko and pycrypt that require installation on the client.
The app used to be here. It can now be found here.
* The official, canonical repository is git.fabfile.org
* The official Github mirror is GitHub/bitprophet/fabric
There are several good articles on it, though you should be careful because it has changed in the last six months:
If you want to avoid any extra modules, you can use the subprocess module to run
ssh [host] [command]
and capture the output.
Try something like:
process = subprocess.Popen("ssh example.com ls", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output,stderr = process.communicate()
status = process.poll()
print output
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.
Like hughdbrown, I like Fabric. Please notice that while it implement its own declarative scripting (for making deploys and the such) it can also be imported as a Python module and used on your programs without having to write a Fabric script.
Fabric has a new maintainer and is in the process of being rewriten; that means that most tutorials you'll (currently) find on the web will not work with the current version. Also, Google still shows the old Fabric page as the first result.
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:
import spur
shell = spur.SshShell(hostname="localhost", username="bob", password="password1")
result = shell.run(["echo", "-n", "hello"])
print result.output # prints hello
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:
result = shell.run(["echo", "-n", "hello"], stdout=sys.stdout)
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.
import base64
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.1.1', username='user', password='password')
stdin, stdout, stderr = client.exec_command('cat /proc/meminfo')
for line in stdout:
print('... ' + line.strip('\n'))
client.close()
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:
import spurplus
with spurplus.connect_with_retries(
hostname='some-machine.example.com', username='devop') as shell:
out = shell.check_output(['/path/to/the/command', '--some_argument'])
print(out)
please refer to paramiko.org, its very useful while doing ssh using python.
import paramiko
import time
ssh = paramiko.SSHClient() #SSHClient() is the paramiko object</n>
#Below lines adds the server key automatically to know_hosts file.use anyone one of the below
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
#Here we are actually connecting to the server.
ssh.connect('10.106.104.24', port=22, username='admin', password='')
time.sleep(5)
#I have mentioned time because some servers or endpoint prints there own information after
#loggin in e.g. the version, model and uptime information, so its better to give some time
#before executing the command.
#Here we execute the command, stdin for input, stdout for output, stderr for error
stdin, stdout, stderr = ssh.exec_command('xstatus Time')
#Here we are reading the lines from output.
output = stdout.readlines()
print(output)
#Below all are the Exception handled by paramiko while ssh. Refer to paramiko.org for more information about exception.
except (BadHostKeyException, AuthenticationException,
SSHException, socket.error) as e:
print(e)