SSH and SFTP with Paramiko & Python

November 23rd, 2014

Paramiko is a Python implementation of SSH with a whole range of supported features. To start, let’s look at the most simple example – connecting to a remote SSH server and gathering the output of ls /tmp/

import paramiko

ssh = paramiko.SSHClient()
        ssh.connect('localhost', username='testuser', password='t3st@#test123')
except paramiko.SSHException:
        print "Connection Failed"

stdin,stdout,stderr = ssh.exec_command("ls /etc/")

for line in stdout.readlines():
        print line.strip()

After importing paramiko, we create a new variable ‘ssh’ to hold our SSHClient. ssh.set_missing_host_key_policy automatically adds our server’s host key without prompting. For security, this is not a good idea in production, and host keys should be added manually. Should a host key change unexpectedly, it could indicate that the connection has been compromised and is being diverted elsewhere.

Next, we create 3 variables, stdin, stdout and stderr allowing us to access the respective streams when calling ls /etc/

Finally, for each “\n” terminated line on stdout, we print the line, stripping the trailing “\n” (as print adds one). Finally we close the SSH connection.

Let’s look at another example, where we communicate with stdin.
Read the rest of this entry »

Escaping BASH variables for sed replace

January 15th, 2010

I came up against an issue in trying to replace a string with sed that contained special characters. Assume the following example:
cat /etc/awstats.template|sed s/TEMPLATE-LOG/$LOG/g

The sed fails because $LOG contains forward slashes. Instead, these must be escaped:

cat /etc/awstats.template|sed “s/TEMPLATE-LOG/$(echo $LOG | sed -e ‘s/\/\\/g’ -e ‘s///\//g’ -e ‘s/&/\&/g’)/g”

This doesn’t escape all special characters. The only characters that we need to escape are the backslash, the forward slash, and the ampersand.

Simple text sorting

April 5th, 2009

On the command line we have a number of powerful tools available to us. I’m going to cover some text sorting methods here.

I have a file called ‘testfile’ within this file is the following:

test:~# cat testfile


this is a test
test file

Read the rest of this entry »

mknod tutorial

October 26th, 2008

mknod is a powerful command with which you can create block or character special files. If you view the man page, you’ll see that you can use it to create block device links and character device links. If you don’t know what these are then don’t worry. The purpose of this tutorial is to explore the FIFO (First In First Out) feature.

A FIFO literally does what it says on the box. The first piece of data to go in is the first piece of data to go out.

The usage of the command is:

Usage: /bin/mknod [OPTION]… NAME TYPE [MAJOR MINOR]

Where MAJOR and MINOR are for the special devices mentioned above.
Read the rest of this entry »