You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无互联网同局域网两台电脑如何用Git同步文件 不可行时Python如何实现

方案1:使用Git实现局域网代码同步(完全可行)

Git本身完全支持局域网内点对点同步,不需要公网远程仓库,操作步骤如下:

PC1(代码源机器)配置

  • 进入本地代码仓库的根目录,执行命令允许其他设备推送内容到当前已检出分支:
    git config --local receive.denyCurrentBranch updateInstead
  • 启动Git自带的局域网守护进程,暴露当前仓库:
    git daemon --reuseaddr --base-path=. --export-all --verbose
    默认监听端口为9418,保持终端运行即可提供服务。

PC2(同步目标机器)操作

  • 先获取PC1的局域网IP地址(比如192.168.3.25),首次拉取代码执行:
    git clone git://192.168.3.25/你的仓库文件夹名
  • 后续PC1提交新代码后,PC2在本地仓库目录执行git pull即可拉取最新变更,也可执行git push把本地修改同步回PC1。

备选安全方案:如果PC1开启了SSH服务,PC2也可以用git clone ssh://PC1用户名@PC1的IP/仓库的绝对路径格式克隆,不需要启动git daemon,支持权限校验。


方案2:Python实现全量文件拷贝

如果不需要代码版本管理,只需要全量同步文件,可以用Python内置模块实现,无需安装第三方依赖:

PC1(源机器)操作

进入要同步的代码根目录,执行命令启动临时HTTP文件服务:
python -m http.server 8000
保持终端运行即可。

PC2(目标机器)同步脚本

运行以下Python脚本即可把PC1目录下的所有文件全量同步到本地指定路径:

import os
import urllib.request
from html.parser import HTMLParser

# 配置项
PC1_IP = "192.168.3.25"  # 替换为PC1的实际局域网IP
PC1_PORT = 8000
LOCAL_SAVE_PATH = "./同步的代码"  # 替换为本地保存路径

class LinkParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.links = []
    def handle_starttag(self, tag, attrs):
        if tag == 'a':
            for attr in attrs:
                if attr[0] == 'href':
                    self.links.append(attr[1])

def sync_dir(remote_path, local_path):
    os.makedirs(local_path, exist_ok=True)
    url = f"http://{PC1_IP}:{PC1_PORT}/{remote_path}"
    with urllib.request.urlopen(url) as res:
        content = res.read().decode('utf-8')
    parser = LinkParser()
    parser.feed(content)
    for link in parser.links:
        if link == '../':
            continue
        remote_sub_path = remote_path + link if remote_path else link
        local_sub_path = os.path.join(local_path, link)
        if link.endswith('/'):
            sync_dir(remote_sub_path, local_sub_path)
        else:
            urllib.request.urlretrieve(f"http://{PC1_IP}:{PC1_PORT}/{remote_sub_path}", local_sub_path)
            print(f"已同步: {remote_sub_path}")

if __name__ == "__main__":
    sync_dir("", LOCAL_SAVE_PATH)
    print("全量同步完成")

注意:该方案为全量覆盖同步,不会做增量差分,也不保留版本历史,适合单次全量拷贝场景。


内容的提问来源于stack exchange,提问作者Guy in 411

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 19:15:01