使用Paramiko SFTP复制目录



我想模仿著名的linux rsync命令的行为,如果未在目录末尾指定"/"并复制所有内容,则它将从" test"复制整个目录在"/"存在时"测试/"内部。我本地的"测试"文件夹是这样的结构:

test
.
├── fileA.txt
├── fileB.txt
├── test1
│   └── test3
│       └── file3.txt
└── test2
    └── file2.txt

将整个本地测试文件夹复制到rsync中的远程服务器:

rsync -avzP test username@remotehost:/home/

在遥控主机的主目录内将是

home
.
|__ test
    ├── fileA.txt
    ├── fileB.txt
    ├── test1
    │   └── test3
    │       └── file3.txt
    └── test2
        └── file2.txt

示例

复制本地"测试"文件夹中的所有内容不包括本身:

rsync -avzP test/ username@remotehost:/home/

主目录的结构是:

home/
.
├── fileA.txt
├── fileB.txt
├── test1
│   └── test3
│       └── file3.txt
└── test2
    └── file2.txt

示例B

我没有工作的代码例如B。我考虑过分开路径并摆脱"测试",然后复制其中的所有内容,但它只会使我进入无尽的嵌套,以获取循环。另一个想法是使用os.listdir。如果是目录,请再次列出目录并复制该目录中的内容。这仍然是循环的另一个无尽的。上面的树结构是一个过度简化的例子,但是在现实生活中,我们都知道目录可能是5个级别。如何实现示例B?

def put (self, localpath, remotepath):
        sftp = self.ssh.open_sftp ()
        # Create remote directory if it doesn't exist
        try:
            sftp.stat (remotepath)
        except FileNotFoundError:
            sftp.mkdir (remotepath)
        if os.path.isfile (localpath):
            # Obtain file name from local path & append to remote path
            path = os.path.split (localpath)        # Returns a tuple (directory, filename)
            remote_filename = os.path.join (remotepath, path [1])
            print ('  Copying %s' % remote_filename)
            sftp.put (localpath, remote_filename)
        elif os.path.isdir (localpath):
            p = os.path.join (remotepath, localpath)
            try:
                sftp.stat (p)
            except FileNotFoundError:
                sftp.mkdir (p)
            for dirpath, dirnames, filenames in os.walk (localpath):
                # Traverse into each child directory and create sub directory if it doesn't exist
                if dirnames:
                    for dirname in dirnames:
                        subdir = os.path.join (dirpath, dirname)
                        try:
                            sftp.stat (subdir)
                        except FileNotFoundError:
                            sftp.mkdir (subdir)
                for filename in filenames:
                    local_filename = os.path.join (dirpath, filename)
                    remote_filename = os.path.join (remotepath, local_filename)
                    sftp.put (local_filename, remote_filename)

我弄清楚了。这不是最漂亮的,而是功能。如果有人有更好,更清洁和更多的Pythonic方法,请分享。

def put (self, localpath, remotepath):
    sftp = self.ssh.open_sftp ()
    # Create remote directory if it doesn't exist
    try:
        sftp.stat (remotepath)
    except FileNotFoundError:
        sftp.mkdir (remotepath)
    if os.path.isfile (localpath):
        # Obtain file name from local path & append to remote path
        path = os.path.split (localpath)        # Returns a tuple (directory, filename)
        remote_filename = os.path.join (remotepath, path [1])
        print ('  Copying %s' % remote_filename)
        sftp.put (localpath, remote_filename)
    elif os.path.isdir (localpath):
        if localpath.endswith ('/'):
            for dirpath, dirnames, filenames in os.walk (localpath):
                # Change local dirpath to match remote path. Ex: local/dir/.. to remote/dir/...
                remotedir = dirpath.split ('/')             # remotedir = [local, dir1, dir2, ...]
                remotedir [0] = remotepath.rstrip ('/')     # remotedir = [/remote, dir1, dir2, ...]
                remotedir = '/'.join (remotedir)
                # Traverse into each child directory and create sub directory if it doesn't exist on remote host
                if dirnames:
                    for dirname in dirnames:
                        subdir = os.path.join (remotedir, dirname)
                        try:
                            sftp.stat (subdir)
                        except FileNotFoundError:
                            sftp.mkdir (subdir)
                for filename in filenames:
                    localdir = os.path.join (dirpath, filename)
                    remotefile = os.path.join (remotedir, filename)
                    print ('  Copying %s' % localdir)
                    sftp.put (localdir, remotefile)
        else:
            # Create path /remote/local/dir1...
            p = os.path.join (remotepath, localpath)
            try:
                sftp.stat (p)
            except FileNotFoundError:
                sftp.mkdir (p)
            for dirpath, dirnames, filenames in os.walk (localpath):
                if dirnames:
                    for dirname in dirnames:
                        subdir = os.path.join (dirpath, dirname)
                        remotedir = os.path.join (remotepath, subdir)
                        try:
                            sftp.stat (remotedir)
                        except FileNotFoundError:
                            sftp.mkdir (remotedir)
                for filename in filenames:
                    local_filename = os.path.join (dirpath, filename)
                    remote_filename = os.path.join (remotepath, local_filename)
                    print (' Copying %s' % local_filename)
                    sftp.put (local_filename, remote_filename)
    else:
        print ('File or directory not found.')

结束结果:

示例A:

>>> ssh.put ('test', '/home/user/')
 Copying test/fileA.txt
 Copying test/fileB.txt
 Copying test/test1/test3/file3.txt
 Copying test/test2/file2.txt
Completed!
-sh-4.1$ ls -lh test/*
-rw-r----- 1 user users    0 Sep  1 23:43 test/fileA.txt
-rw-r----- 1 user users    0 Sep  1 23:43 test/fileB.txt
test/test1:
total 4.0K
drwxr-x--- 2 user users 4.0K Sep  1 23:43 test3
test/test2:
total 0
-rw-r----- 1 user users 0 Sep  1 23:43 file2.txt
-sh-4.1$ ls -lh test/*/*
-rw-r----- 1 user users    0 Sep  1 23:43 test/test2/file2.txt
test/test1/test3:
total 0
-rw-r----- 1 user users 0 Sep  1 23:43 file3.txt
-sh-4.1$ 

示例B:

>>> ssh.put ('test/', '/home/user/')
  Copying test/fileA.txt
  Copying test/fileB.txt
  Copying test/test1/test3/file3.txt
  Copying test/test2/file2.txt
Completed!
-sh-4.1$ pwd
/home/user
-sh-4.1$ ls -lh
total 108K
-rw-r----- 1 user users    0 Sep  1 23:43 fileA.txt
-rw-r----- 1 user users    0 Sep  1 23:43 fileB.txt
drwxr-x--- 3 user users 4.0K Sep  1 23:43 test1
drwxr-x--- 2 user users 4.0K Sep  1 23:43 test2
-sh-4.1$ ls -lh test1 test2
test1:
total 4.0K
drwxr-x--- 2 user users 4.0K Sep  1 23:43 test3
test2:
total 0
-rw-r----- 1 user users 0 Sep  1 23:43 file2.txt
-sh-4.1$ ls -lh test1/test3/
total 0
-rw-r----- 1 user users 0 Sep  1 23:43 file3.txt
-sh-4.1$ 

最新更新