使用 python 比较远程目录和本地目录中的文件

comapare files that are on remote directory and local directory using python

我在这个网站上得到了一个代码,可以从服务器的远程目录下载文件。现在我想修改这段代码,以便它比较远程目录而不是本地目录上的文件和列表。它列出了远程目录和本地目录之间不常见的文件。 这可能吗? 请帮忙。提前致谢

import os
import pysftp
import socket
from stat import S_IMODE, S_ISDIR, S_ISREG

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None

IP = "192.168.X.X"
myUsername = "user"
port = 22
myPassword = "password"

try:
    with pysftp.Connection(host=IP, username=myUsername, password=myPassword, cnopts=cnopts) as sftp:
        try:
            r=str(socket.gethostbyaddr(IP))
            print("connection successful with "+r)


            def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
                for entry in sftp.listdir(remotedir):
                    remotepath = remotedir + "/" + entry
                    localpath = os.path.join(localdir, entry)
                    mode = sftp.stat(remotepath).st_mode
                    if S_ISDIR(mode):
                        try:
                            os.mkdir(localpath, mode=777)
                        except OSError:
                            pass
                        get_r_portable(sftp, remotepath, localpath, preserve_mtime)
                    elif S_ISREG(mode):
                        sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)


            remote_path = input("enter the remote_path: ")
            local_path = input("enter the local_path: ")

            get_r_portable(sftp, remote_path, local_path, preserve_mtime=False)
        except socket.herror:
            print("Unknown host")
except:
    print("connection failed")

结果应该是出现在远程目录中而不是本地目录中的不常见文件。

如果要下载新文件和不在本地系统上的文件,请使用 rsync。您可以将本地目录与远程目录同步,如下所示:

rsync -a ~/dir1 username@remote_host:destination_directory

如何在 python 中使用它:

import subprocess

args = ["rsync", "-av", "-e", "ssh", "user@server:/tmp/", "/home/local/Desktop/"]
subprocess.call(args)

你可以通过 --password-file 开关,它必须指向一个包含 ssh 密码的文件,或者你可以使用 ssh 密钥。

def getFilesList(path):
files = []
for (dirpath, dirnames, filenames) in os.walk(path):
    files.extend(filenames)
    return files
ServerFiles = getFilesList(Srverpath)
LocalFiles = getFilesList(Lclpath) 
fileDiffList = []
for file in ServerFiles: 
    if file in LocalFiles: 
        pass 
    else:
        fileDiffList.append(file) 

我们可以使用2个单独的列表来获取不常见的文件。 通过传递您的服务器路径和本地文件路径来调用 getFilesList 方法两次。 最后你的 'fileDiffList' 将有文件名