Spot any errors? let me know, but Unleash your pedant politely please.

Monday 9 December 2013

SFTP Python Paramiko (and some of the problems I had)

I needed to rename a file on a RHEL server as part of some test automation scripts.  Hope this helps.

I used paramiko to do it with SFTP.  I pretty much copied some code from Stack Exchange to make this:

import paramiko

class SingleCommandSFTP(object):
    def __init__(self,
                 host,
                 username,
                 password,
                 port = 22):

        self.host = host
        self.username = username
        self.password = password
        self.port = port
        
        
    def _open(self):
        self.transport = paramiko.Transport((self.host,
                                             self.port))
        self.transport.connect(username = self.username,
                               password = self.password) 
        self.sftp_client = paramiko.SFTPClient.from_transport(self.transport)

        
    def _close(self):
        self.sftp_client.close()
        self.transport.close()
        
    def rename(self,
               source,
               destination):
               
        self._open()
        self.sftp_client.rename(oldpath = source,
                                newpath = destination)
        self._close()

    # Add further commands as and when required.

It only has rename, but that's all I need for now. It would probably be worth making a decorator for the _open / _close functions if many more functions were to be added, but I don't quite know how to do that (yet).

Problems (Mac):

If you try to easy_install paramiko on Mavericks, it'll probably fail because it can't compile pycrypto.  You need to install Xcode and fiddle about a bit (Found at Stack Exchange and Abakas):
  • In Xcode, go Preferences > Downloads, and click on the "Install" button next to "Command Line Tools" to install the compiler needed by Python.
  • sudo ln -s /usr/bin/gcc /usr/bin/gcc-4.2
I also got this at some point: warning: GMP or MPIR library not found; Not building Crypto.PublicKey._fastmath. Unfortunately I can't remember what I did to fix that.


Problems (Windows):

On Windows, it wasn't practical to install a suitable compiler to build pycrypto from source.  I used the 32-bit installer for Python 2.7 (downloads are here).   I had installed Python for all users, but that caused another problem solved by Stack Exchange.  I uninstalled Python an installed for the user only.

I also had to install the ECDSA cryptographic signature library as this wasn't found when importing paramiko.

No comments:

Post a Comment