Wednesday, January 12, 2011

SSH with Python

To use SSH with Python, we can use library like paramiko. That library depends on pycrypto, which is mostly a C library. Thus, we need to make sure that we have a C compiler. To install paramiko on Linux/Ubuntu, it's very straightforward.
sudo apt-get install python-paramiko
However, on Windows, we need a little bit of work. By default, distutils on Windows requires Visual Studio compiler.
1. Download Microsoft Visual Studio Express 2008.
2. Download Windows SDK and install the Windows Headers and Libraries.
pyconfig.h requires header files, such as basetsd.h that's available in Windows SDK.
3. Download pycryto library.
4. From the command line, go to pycrypto folder and type
python setup.py install
5. Download paramiko library.
6. From the command line, go to paramiko folder and type
python setup.py install

Below is the sample. The code is pretty self-explanotary.
import paramiko

def do_ssh(hostname, username, password):
    client = paramiko.SSHClient()
    try:
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(hostname, 22, username, password)
        stdin, stdout, stderr = client.exec_command('ls -l')
        print stdout.read()
    finally:
        client.close()

if __name__ == "__main__":
    do_ssh("hostname", "username", "password")

No comments:

Post a Comment