SSH in Python: A Quick Working Sample

In one of my recent consulting projects, I had to use SSH from Python. After a little research, I ended up with using the paramiko package as library.

Installing Libraries

To download the paramiko package, just check out this link. What I downloaded was paramiko-1.12.0.tar.gz. After it’s uncompressed with 7-Zip to a temparary directory, just issue the following command and the needed library got installed into the site-packages directory.

C:\Dev\python27\python.exe setup.py install

That is not enough as I found out through a series of import errors. To make the paramiko package work, two dependent packages are needed: PyCrypto and ecdsa. The installation of the PyCrypto is straight-forward with an installer from this site. I first downloaded the 64 bit but didn’t seem to work well as it could not find my Python installation home. I then tried the 32 bit (pycrypto-2.6.win32-py2.7.exe) and worked well.

The ecdsa is a bit interesting. A quick search got me the project home on the GitHub right away, and then some description there concerned me as it mentioned support for Python 3.x. After going through a few issues with Python compatibility from version to version, I was not sure if I wouldn’t run into issues. Regardless, I downloaded the zip (python-ecdsa-master.zip) from master branch anyway. Without typical setup.py, I just copied the ecdsa folder to the site-packages folder, and it worked magically.

That is all about the installation of needed libraries.

Sample to Run Remote Shell Command

Let’s now take a look at the working sample code. To run it, you want to change the IP address and password to your Linux machine.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
__author__ = 'Steve Jin'
 
import paramiko
 
def runSshCmd(hostname, username, password, cmd, timeout=None):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(hostname, username=username, password=password,
            allow_agent=False, look_for_keys=False, timeout=timeout)
 
    stdin, stdout, stderr = client.exec_command(cmd)
    data = stdout.read()
    print data
 
    client.close()
 
runSshCmd("192.168.16.8", "root", "cloud", "uname -a")

As you can see, the code has one function that takes host, credentials, and a command to be executed. The last line calls the function with needed information. If you have many commands to run in a row, you can change the design a bit so that you don’t connect and close for each command.

Troubleshooting

Besides several import errors that pointed me to additional packages, I also got the following error in the end just before it started to work:

paramiko.SSHException: No authentication methods available

The code that leads to this error is slightly different as follows:

    client.connect(hostname, username, password, allow_agent=False, look_for_keys=False)

After debugging into it, I found the underlying library got password as None. It turned out one of the parameter names is exactly called parameter and my arguments order does not match the API, therefore it assumed that password is None. A silly mistake. Changing it to password = password solved the problem.

This entry was posted in Software Development and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

4 Comments

  1. Al
    Posted January 5, 2014 at 12:39 am | Permalink

    Thank you very much..I am just wondering how can modify the script if I have so may routersto access , and I wanted the script to read the host names from a file.

    Thanks

  2. Posted January 5, 2014 at 3:44 pm | Permalink

    You are welcome Al,

    I believe you can find many script samples on reading strings from a file. Not clear about “so ma(n)y routers to access.” Can you elaborate?

    Also, I offer consulting and training services. If you are interested, please let me know.

    Steve

  3. Posted January 22, 2014 at 4:09 pm | Permalink

    Hi Steve,

    I’m looking to solve a console access problem. My customers are asking for console access via ssh and rpc to their hybrid cloud environments.. VMware – Linux, Windows, AWS, Openstack and others. Ideally, my customers would be able to order and provision an image and then be able to click on a console access link to A. Watch the installation process of an OS, or B. Get terminal access to the image once it’s up and running. I would like to build console access solution into our application that’s vendor neutral, yet retains the flexibility and functionality that my customers are looking for. I know that there are several hurdles that I need to overcome.. such as ssh pub / private key mgmt for the public CPS’s, which API’s to use etc. I’m looking for your guidance and thought on the matter.

    Thank you,

    Hani.

  4. Posted January 23, 2014 at 12:45 am | Permalink

    Hi Hani,

    If your customers want to use SSH for connecting to their virtual machines, the cloud is out of picture except the initial OS installation process. There is no difference for SSH to connect to a physical machine, or a virtual machine within enterprise or by cloud provider. Most likely, customers don’t install OS by themselves – they just clone from an existing, and hopefully well tested, template with OS already installed.

    The tricky part comes when they want to have password less access because it involves the key management. Different providers may have different ways/APIs to do it. I am sure you can unify them for a single and easy to use solution.

    Good luck!

    Steve

One Trackback

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • NEED HELP?


    My consulting helps clients with virtualization and cloud computing, including VMware infrastructure automation and orchestration, vSphere management APIs, and deep product integration with hypervisors. Current training offerings include vSphere APIs training, vCenter Orchestrator training, and etc. Should you, or someone you know, need these consulting services or training, please feel free to contact me: steve __AT__ doublecloud.org.

    Me: Steve Jin, VMware vExpert who authored the VMware VI and vSphere SDK by Prentice Hall, and created the de factor open source vSphere Java API while working at VMware engineering. Companies like Cisco, EMC, NetApp, HP, Dell, VMware, are among the users of the API and other tools I developed for their products, internal IT orchestration, and test automation.