March 21, 2019

Scripting SSH and SFTP Made Easy With Python - page 2

Secure, Automated SSH and SFTP Sessions

  • December 16, 2008
  • By Jeremy M. Jones

Now, we can get to something that is a little more useful. Sometimes you may want to execute a command on a remote system and gather the output from the command. The following example executes an "ls" command on the remote server that we connected to in the previous examples.

#!/usr/bin/env pythonfrom __future__ import with_statement
import ssh_commonwith ssh_common.create_ssh() as ssh:
���cmd = 'ls -l /home/slacker/files'
��� stdin, stdout, stderr = ssh.exec_command(cmd) print "STDOUT" print "+" * 40
��� print stdout.read()
��� print "-" * 40 print "STDERR"
��� print "+" * 40
��� print stderr.read()
��� print "-" * 40

The only thing this example does differently with the "ssh" object from the previous example is that it calls the "exec_command()" method on it. The command I passed in was "ls -l /home/slacker/files". "exec_command()" returns a tuple containing the standard input, output, and error of the remote process. The rest of the code prints the standard output and standard error from the remote execution. Here is what happens when I run the script:

jmjones: python_ssh$ python simple_exec.py
creating connection
total 48
-rw-rw-r-- 1 slacker slacker 5855 Nov 19 19:15 a.txt
-rw-rw-r-- 1 slacker slacker 5855 Nov 19 19:15 b.txt
-rw-rw-r-- 1 slacker slacker 5855 Nov 19 19:15 c.txt
-rw-rw-r-- 1 slacker slacker 5855 Nov 19 19:15 d.txt----------------------------------------
closing connection

The script displayed the listing of four files: "a.txt", "b.txt", "c.txt", and "d.txt". The file listing came from stdout and nothing came from stderr. I wrote this script so that it would do a file listing in order to tie into the next examples, but you could replace that "ls" command with anything: a "ps" command to check for running processes, a "netstat" command to see if any process is binding a specific port, or a "df" command to check free disk space.

Now, on to something else useful. I commonly use SSH to transfer files between servers using SSH. Actually, I use SFTP or SCP, but these are parts of SSH. The following module contains a function that takes an "ssh" object and returns an "sftp" object wrapped in context manager goodness.

> #!/usr/bin/env pythonfrom contextlib import contextmanager@contextmanager
def create_sftp(ssh):
��� try:
��� ��� print "creating sftp"
��� ��� sftp = ssh.open_sftp()
��� ��� print "created" yield sftp
��� finally:
��� print "closing sftp"
��� sftp.close()
��� print "sftp closed"

And here is a script that uses the "ssh" and "sftp" context managers and retrieves the files in "/home/slacker/files".

#!/usr/bin/env pythonfrom __future__ import with_statement
import ssh_common
import sftp_common
import oswith ssh_common.create_ssh() as ssh:
��� with sftp_common.create_sftp(ssh) as sftp:
��� � sftp.chdir('/home/slacker/files')
��� � for f in sftp.listdir():
��� � ��� � print "retrieving", f
��� � ��� � sftp.get(f, os.path.join('files', f))

This script is pretty straightforward. At the beginning of the outer "with" block, the script creates an "ssh" object. At the beginning of the inner "with" block, the script creates an "sftp" object. Inside the inner "with" block, the script changes directory to "/home/slacker/files", then does a directory listing and retrieves each of the files listed. When the file retrieval part is finished, the context managers execute the "finalization" code, closing the "sftp" and "ssh" connections.

Here is the result of running the "sftp" script:

jmjones: python_ssh$ python simple_xfer.py
creating connection
creating sftp
retrieving d.txt
retrieving c.txt
retrieving a.txt
retrieving b.txt
closing sftp
sftp closed
closing connection closed

paramiko makes the possibilities for SSH automation truly mind boggling. paramiko also simplifies connecting to an SSH server from some Python code you have already written. If you have to interact with SSH servers on a regular basis, download paramiko and play around with it. It's bound to simplify your work.

Related Articles:

Have a Bash With This Linux Shell
Scripting Best Practices
OpenSSH Speed Tips and Tricks

Article courtesy of Enterprise IT Planet

Most Popular LinuxPlanet Stories