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

背景:在远程服务器改代码并测试后(因为账号问题不允许直接 git),希望将更改同步到本地设备然后 git push 到代码仓库

方法

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

流程

  1. 在 mac 设置中找到 通用→ 共享→ 高级→远程登录,勾选☑️ ,设置允许访问用户(同时可以查看到设备 IP 地址)

  2. 实现无密码登录

    在远程服务器上生成 SSH 密钥对,ssh-keygen -t rsa -b 4096, 默认保存在 ~/.ssh/id_rsa,查看公钥cat ~/.ssh/id_rsa.pub,复制内容。

    在本地目录新建~/.ssh/authorized_keys,在authorized_keys中粘贴上一步的内容。

  3. 测试无密码连接

    在远程服务器下新建脚本,主要函数如下,通过 git diff比较远程机器和代码仓库的差异,然后将差异文件 scp 到本地设备。

主要代码如下:

python 复制代码
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 函数传输。

相关推荐
渲染101专业云渲染几秒前
川翔云电脑优势总结
服务器·3d·电脑·blender·maya
chian-ocean18 分钟前
Linux 文件缓冲区:高效数据访问的幕后推手
linux·运维·服务器
加油=^_^=20 分钟前
【Linux】进程优先级 | 进程调度(三)
linux·运维·服务器
橘子味的茶二30 分钟前
高级系统架构师--第十章:计算机网络
服务器·计算机网络·系统架构
紫菜(Nori)1 小时前
短连接服务器压测-wrk
服务器·压力测试
元气满满的热码式1 小时前
Docker数据卷操作实战
linux·运维·docker·云原生·容器
陆沙1 小时前
deepseek-r1-centos-本地服务器配置方法
linux·服务器·centos
北京耐用通信1 小时前
航空装配自动化神器Ethercat转profient网关搭配机器人精准控制
运维·机器人·自动化
吃汤圆的抹香鲸1 小时前
Rider 安装包 绿色版 Win/Mac/Linux 适合.NET和游戏开发者使用 2025全栈开发终极指南:从零配置到企业级实战
linux·运维·windows·sql·游戏·macos·.net
崔lc4 小时前
linux中安装部署Jenkins,成功构建springboot项目详细教程
运维·jenkins