Linux and UNIX How To: Scripting SSH and SFTP: Page 2

(Page 2 of 2)

Continued from Page 1.

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 python

from __future__ import with_statement
import ssh_common

with 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 python

from contextlib import contextmanager

def create_sftp(ssh):
        print "creating sftp"
        sftp = ssh.open_sftp()
        print "created"

        yield sftp
        print "closing sftp"
        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 python

from __future__ import with_statement
import ssh_common
import sftp_common
import os

with ssh_common.create_ssh() as ssh:
    with sftp_common.create_sftp(ssh) as sftp:
        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

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.

This article was first published on EnterpriseITPlanet.com.

Page 2 of 2

Previous Page
1 2

Comment and Contribute


(Maximum characters: 1200). You have characters left.



IT Management Daily
Don't miss an article. Subscribe to our newsletter below.

By submitting your information, you agree that datamation.com may send you Datamation offers via email, phone and text message, as well as email offers about other products and services that Datamation believes may be of interest to you. Datamation will process your information in accordance with the Quinstreet Privacy Policy.

We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.