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

背景:在远程服务器改代码并测试后(因为账号问题不允许直接 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 函数传输。

相关推荐
YoungStudyAI4 小时前
QA的下一个自动化阶段,可能不是再写更多脚本,而是设计测试Agent
运维·自动化
筝筝ba5 小时前
openBMC功耗封顶GUI测试
服务器
分布式存储与RustFS5 小时前
纠删码到底吃掉了多少容量:EC:4、EC:8 的利用率与容错怎么算
运维·云原生·开源·对象存储·分布式存储·s3·性能基准
遇见小修修5 小时前
3步解决打印机0x00000709报错 ,广州深圳程序员可自行排查
运维·打印机·维修·打印机报错·打印机运维·打印机故障自查
niuTaylor6 小时前
飞腾 FT-2000/4 Ubuntu 内存卡 / NVMe SSD 系统制作完整指南
linux·服务器·人工智能·驱动开发·单片机
Huangjin007_7 小时前
【Linux 系统篇(二十五)】文件(二) 系统文件I/O详解
linux·运维·服务器
微小冷7 小时前
Mermaid画甘特图
运维·markdown·甘特图·mermaid·时间图
云表无代码开发8 小时前
日本开发者彻底破防:中文太强了!换成英文直接裂开
大数据·服务器·人工智能·microsoft·信息可视化
LBL12208 小时前
内网容器部署FTP日志监控服务
运维·服务器·容器
志栋智能8 小时前
超自动化巡检:驱动持续改进的运维飞轮
运维·自动化