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

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

相关推荐
望获linux3 小时前
【实时Linux实战系列】硬实时与软实时设计模式
linux·运维·服务器·数据库·操作系统·rtos·嵌入式软件
沉默的八哥6 小时前
Linux中LVM逻辑卷扩容
linux·运维·服务器
YZJenny6 小时前
没有管理员权限,在服务器安装使用 Jupyter + R 内核
服务器·jupyter
wanhengidc7 小时前
服务器机柜与网络机柜各自的优势
服务器·网络·智能路由器
Otaku love travel7 小时前
实施运维文档
运维·windows·python
basketball6168 小时前
Linux C 管道文件操作
linux·运维·c语言
颖川初尘8 小时前
端口到底是个什么鬼?回答我!
服务器·网络·tcp/ip·node.js
浩浩测试一下8 小时前
Windows 与 Linux 内核安全及 Metasploit/LinEnum 在渗透测试中的综合应用
linux·运维·windows·web安全·网络安全·系统安全·安全架构
stark张宇8 小时前
Linux 文件创建、删除、移动、复制基础知识整理
linux·服务器·centos
将心ONE9 小时前
使用 lstrip() 和 rstrip() 方法
运维·服务器