[paramiko] retrieving remote file via paramiko/scp

erick_bodine at comcast.net erick_bodine at comcast.net
Tue Oct 30 12:14:40 PDT 2007


There was a thread earlier in the year (May) about sending a file using "scp" and paramiko which was very helpfull.  I found the need to do the reverse action and came up with the following solution.  It is more than a little rough and currently only works one file at a time, so no directory recursion.  Feel free to comment/use.


def read_file(self, remote_file, local_file=None):
       
    chan = self._trans.open_session()
    chan.exec_command("scp -v -f %s" % remote_file)
    
    # Send \0
    chan.send('\0')
    
    filesize=''
    rfilename=''

    while True:
        # Ack
        chunk = chan.recv(1)
        
        if chunk != 'C':
            print "Ack error [%s]: Does the remote file exist??" % chunk
            break

        # read file permissions ie.'0644'
        permissions = chan.recv(5)
        
        # Get the size of the remote file.
        buf = ''
        while True:
            chunk = chan.recv(1)
            
            if chunk < 0:
                print "error "; break

            if chunk == ' ' or chunk == '\n':
                break
            else:
                buf = buf + chunk

        filesize = int(buf)
        
        # Get the remote filename.
        buf=''
        while True:
            chunk = chan.recv(1)
            
            if chunk < 0:
                print "error "; break

            if chunk == ' ' or chunk == '\n':
                break
            else:
                buf = buf + chunk

        rfilename = buf
        
        print "filesize: %d, mode: %s, filename: %s" % (filesize, permissions, rfilename)
        
        # Send \0, again.
        chan.send('\0')

        # Read the file contents
        total = 0
        read_chunk = 1024
        
        if local_file:
            rfilename = local_file
        fh = open(rfilename, 'wb')
            
        while total <= filesize: 
            chunk = chan.recv(read_chunk)
            fh.write(chunk)
            total = total+read_chunk

        fh.truncate(filesize)
        fh.close()
        chan.send('\0')
        break
    
    print "got all the chunks?"
    chan.send('\0')
    chan.close()
    t.close()



--
--ERick



More information about the paramiko mailing list