Directory transfers with Paramiko

前端 未结 10 894
刺人心
刺人心 2020-11-30 07:25

How do you use Paramiko to transfer complete directories? I\'m trying to use:

sftp.put(\"/Folder1\",\"/Folder2\")

which is giving me this e

10条回答
  •  臣服心动
    2020-11-30 08:02

    This is my first StackOverflow answer. I had a task today which is similar to this. So, I tried to find a direct way to copy entire folder from windows to linux using python and paramiko. After a little research, I came up with this solution which works for smaller size folders with subfolders and files in it.

    This solution first makes the zip file for the current folder (os.walk() is very much helpful here), then copies to destination server and unzip there.

    zipHere = zipfile.ZipFile("file_to_copy.zip", "w")
    
    for root, folders, files in os.walk(FILE_TO_COPY_PATH):
        for file in files:
            zipHere.write(os.path.join(root, file), arcname=os.path.join(os.path.relpath(root, os.path.dirname(FILE_TO_COPY_PATH)), file))
        for folder in folders:
            zipHere.write(os.path.join(root, folder), arcname=os.path.join(os.path.relpath(root, os.path.dirname(FILE_TO_COPY_PATH)), folder))
    zipHere.close()
    
    # sftp is the paramiko.SFTPClient connection
    sftp.put('local_zip_file_location','remote_zip_file_location')
    
    # telnet_conn is the telnetlib.Telnet connection
    telnet_conn.write('cd cd_to_zip_file_location')
    telnet_conn.write('unzip -o file_to_copy.zip')
    

提交回复
热议问题