开发者

Paramiko SFTP - Avoid having to specify full local filename?

开发者 https://www.devze.com 2023-03-31 04:18 出处:网络
I have some Python code that uses Paramiko to grab build files from a remote server: def setup_sftp_session(self, host=\'server.com\', port=22, username=\'puppy\'):

I have some Python code that uses Paramiko to grab build files from a remote server:

def setup_sftp_session(self, host='server.com', port=22, username='puppy'):
    self.transport = paramiko.Transport((host, port))
    privatekeyfile = os.path.expanduser('~/.ssh/id_dsa')
    try:
        ssh_key = paramiko.DSSKey.from_private_key_file(privatekeyfile)
    except IOError, e:
        self.logger.error('Unable to find SSH keyfile: %s' % str(e))
        sys.exit(1)
    try:
        self.transport.connect(username = username, pkey = ssh_key)
    except paramiko.AuthenticationException, e:
        self.logger.error("Unable to logon - are you sure you've added the pubkey to the server?: %s" % str(e))
        sys.exit(1)
    self.sftp = paramiko.SFTPClient.from_transport(self.transport)
    self.sftp.chdir('/some/location/buildfiles')

def get_file(self, remote_filename):
    try:
        self.sftp.get(remote_filename, 'I just want to save it in the local cwd')
    except IOError, e:
        self.logger.error('Unable to find copy remote file %s' % str(e))

def close_sftp_session(self):
    self.sftp.close()
    self.transport.close()

I'd like to retrieve each file, and deposit it in the current local working direc开发者_如何学Pythontory.

However, Paramiko doesn't seem to have an option for this - you need to specify the full local destination. You can't even specify a directory (e.g. "./", or even "/home/victorhooi/files") - you need the full path including filename.

Is there any way around this? It'll be annoying if we have to specify the local filename as well, instead of just copying the remote one.

Also - the way I'm handling exceptions in setup_sftp_session, with exit(1) - is that a good practice, or is there a better way?

Cheers, Victor


you have to insert

os.path.join(os.getcwd(), remote_filename)

Calling exit() in a function is not a good idea. Maybe you want to reuse the code and take some action in case of an exception. If you keep the exit() call you are lost. I suggest to modify this function such that a True is returned in case of success, and False else. Then the caller can decide what to do.

Another approach would be not to catch the exceptions. So the caller has to handle them and the caller gets the full information (including the stacktrace) about the circumstances of the failure.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号