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

如何配置systemd实现开机自动执行git pull?

解决systemd开机自动执行git pull失败的问题

从错误日志里的fatal: could not read Username for 'https://gitlab.com': No such device or address可以明确问题:systemd在系统启动时以无交互的系统上下文运行,无法获取Git仓库的认证信息,导致git拉取操作失败。下面提供两种可靠的解决方案:

方案一:使用SSH密钥免密认证(推荐,更安全)

这是最稳定的方式,避免依赖凭证存储的问题:

  • 生成SSH密钥对(如果还没有):
    ssh-keygen -t ed25519 -C "your-work-email@example.com"
    
    按回车默认完成生成,密钥会存在/home/ubuntu/.ssh/目录下。
  • 将公钥内容(/home/ubuntu/.ssh/id_ed25519.pub里的文本)添加到GitLab账号的SSH密钥列表中(GitLab后台→Settings→SSH Keys)。
  • 修改仓库的远程地址为SSH格式:
    cd /home/ubuntu/app/xxx
    git remote set-url origin git@gitlab.com:<你的用户名>/<你的仓库名>.git
    
  • 手动测试脚本是否能正常运行:
    /home/ubuntu/sched_server_run.sh
    
    确认无报错后,重新加载systemd配置并重启服务:
    sudo systemctl daemon-reload
    sudo systemctl restart gitpull.service
    

方案二:配置Git凭证存储(适用于保留HTTPS地址的场景)

如果坚持用HTTPS地址,可以让Git记住认证凭证,同时确保systemd以正确用户运行:

  • 先手动执行一次git pull,输入GitLab的用户名和密码完成认证,然后配置Git永久存储凭证:
    git config --global credential.helper store
    
    凭证会被保存到/home/ubuntu/.git-credentials文件中。
  • 修改你的systemd服务文件,添加User字段,确保服务以ubuntu用户运行(这样才能读取到用户目录下的凭证文件):
    [Unit]
    Description=git pull models
    Requires=network.target
    After=network.target
    
    [Service]
    Type=simple
    User=ubuntu
    ExecStart=/home/ubuntu/sched_server_run.sh
    WorkingDirectory=/home/ubuntu/app/xxx
    
    [Install]
    WantedBy=multi-user.target
    Alias=pullformodels.service
    
  • 重新加载配置并重启服务:
    sudo systemctl daemon-reload
    sudo systemctl restart gitpull.service
    

额外检查项

  • 确保脚本有可执行权限:
    chmod +x /home/ubuntu/sched_server_run.sh
    
  • 可以启用服务的日志持久化,方便后续排查:在[Service]段添加StandardOutput=journal+console,这样日志会完整保留在journalctl中。

内容的提问来源于stack exchange,提问作者Sigma65535

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 22:27:49