您的当前位置:首页正文

远程服务器文件和本地文件同步的一个方法

2024-11-11 来源:个人技术集锦

方法

使用 scp 将远程服务器代码同步到本地设备

流程

主要代码如下:

import subprocess

def git_diff_name():
    result = subprocess.run(['git', 'diff', '--name-only'], stdout=subprocess.PIPE, text=True, check=True)
    file_paths = result.stdout.strip().splitlines()
    # Use list comprehension to filter out any empty paths and return the paths and filenames
    return [(file, os.path.dirname(file)) for file in file_paths if file]


def transfer_file(file_name, remote_user, ip_address, remote_path):
    scp_command = ["scp", file_name, f"{remote_user}@{ip_address}:{remote_path}"]
    try:
        # It's better to use a list for subprocess commands instead of a single string
        subprocess.run(scp_command, check=True)
        print(f"File '{file_name}' successfully !!! \n\t\t transferred to {remote_path}")
    except subprocess.CalledProcessError as e:
        print(f"Error occurred while transferring file '{file_name}': {e}")

通过调git_diff_name 函数获取文件差异, 然后通过 transfer_file 函数传输。

Top