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

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

相关推荐
web2u18 分钟前
Docker入门及基本概念
java·运维·服务器·spring·docker·容器
元气满满的热码式1 小时前
Docker实战-使用docker compose搭建博客
运维·docker·容器
Anna_Tong2 小时前
阿里云如何协助解决操作系统兼容性问题
linux·服务器·ubuntu·阿里云·centos·云计算·系统迁移
HaoHao_0102 小时前
如何将MySQL数据库迁移至阿里云
服务器·数据库·阿里云·云计算·云服务器·迁移
不良人天码星2 小时前
Linux的基础指令和环境部署,项目部署实战(下)
linux·运维·服务器
火一线3 小时前
【ASP .NET Core】ASP .NET Core介绍
服务器·游戏·.netcore
EasyNVR3 小时前
基于WebRTC与AI大模型接入EasyRTC:打造轻量级、高实时、强互动的嵌入式音视频解决方案
运维·服务器·微信·小程序·webrtc·p2p·智能硬件
技术小齐4 小时前
网络运维学习笔记 022 HCIA-Datacom新增知识点03园区网典型组网架构及案例实战
运维·网络·学习
Java潘老师4 小时前
Automa 浏览器自动化编排 实现自动化浏览器操作
运维·自动化
waves浪游4 小时前
Linux基本指令(上)
linux·运维·服务器