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

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

相关推荐
知更鸟呆呆11 分钟前
【Linux操作系统】基础开发工具(yum、vim、gcc/g++)
linux·运维·vim
Gold Steps.1 小时前
Docker容器部署elasticsearch8.*与Kibana8.*版本使用filebeat采集日志
运维·docker·云原生·es
weixin_461259411 小时前
[C]C语言日志系统宏技巧解析
java·服务器·c语言
m0_637146931 小时前
C语言基础面试问答
运维·服务器
Clownseven2 小时前
SSH/RDP无法远程连接?腾讯云CVM及通用服务器连接失败原因与超全排查指南
服务器·ssh·腾讯云
ricky_fan2 小时前
window下配置ssh免密登录服务器
运维·服务器·ssh
地衣君2 小时前
Ubuntu 配置使用 zsh + 插件配置 + oh-my-zsh 美化过程
linux·运维·ubuntu
2401_858286112 小时前
OS11.【Linux】vim文本编辑器
linux·运维·服务器·编辑器·vim
朱包林3 小时前
day27-shell编程(自动化)
linux·运维·服务器·网络·shell脚本
钢铁男儿3 小时前
一文掌握 Tombola 抽象基类的自动化子类测试策略
运维·自动化