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

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

相关推荐
The森16 小时前
Linux IO 模型纵深解析 01:从 Unix 传统到 Linux 内核的 IO 第一性原理
linux·服务器·c语言·经验分享·笔记·unix
文艺理科生Owen16 小时前
Nginx 路径映射深度解析:从本地开发到生产交付的底层哲学
运维·nginx
期待のcode16 小时前
Redis的主从复制与集群
运维·服务器·redis
翼龙云_cloud16 小时前
腾讯云代理商: Linux 云服务器搭建 FTP 服务指南
linux·服务器·腾讯云
REDcker16 小时前
gRPC开发者快速入门
服务器·c++·后端·grpc
江湖有缘17 小时前
零基础入门:使用 Docker 快速部署 Organizr 个人主页
java·服务器·docker
wangjialelele17 小时前
Linux下的IO操作以及ext系列文件系统
linux·运维·服务器·c语言·c++·个人开发
HypoxiaDream17 小时前
LINUX-Ext系列⽂件系统
linux·运维·服务器
小毛驴85018 小时前
Linux curl 命令用法
linux·运维·chrome
李斯啦果18 小时前
【Linux】Linux目录配置
linux·运维·服务器