场景
在 Ubuntu 服务器上部署新项目时,经常要:
- 生成专用 SSH 密钥
- 写入
~/.ssh/config - 初始化 Git 仓库并绑定远程地址
- 把公钥添加到 GitHub / Gitee / GitLab 的 Deploy keys
手动做容易漏步骤。项目里提供了一个一键脚本。
工具位置
tool/git-ssh-init/init-git-ssh.sh
使用方法
交互模式(推荐)
chmod +x tool/git-ssh-init/init-git-ssh.sh
bash tool/git-ssh-init/init-git-ssh.sh
按提示输入:
| 项 | 说明 | 默认值 |
|---|---|---|
| 项目名称 | 如video |
无 |
| 仓库名称 | 如api、web |
api |
| 仓库 SSH 地址 | 如git@github.com:org/video-api.git |
无 |
| 分支名 | 默认分支 | master |
| 项目目录 | 代码存放路径 | /www/wwwroot/{项目名} |
命令行模式
bash tool/git-ssh-init/init-git-ssh.sh \
--project video \
--repo api \
--url git@github.com:your-org/video-api.git \
--branch master \
--dir /www/wwwroot/video
脚本会自动完成
- 在
~/.ssh/生成密钥对:{项目名}-{仓库名}/{项目名}-{仓库名}.pub - 向
~/.ssh/config写入 Host 配置(含IdentitiesOnly yes,避免串钥) - 创建项目目录(不存在则自动建)
git init并设置origin远程- 输出 公钥内容,复制到 Git 仓库 Settings → Deploy keys
Git 初始化时的安全提示(常见)
Git 2.35 之后,如果目录属主和当前用户不一致(宝塔 / root / www 混用很常见),可能看到:
fatal: detected dubious ownership in repository at '/www/wwwroot/xxx'
原因: Git 认为该目录可能被他人篡改,拒绝操作。
脚本已自动处理: 执行时会写入
git config --global --add safe.directory "/www/wwwroot/你的项目"
若仍报错,手动执行一次即可:
git config --global --add safe.directory /www/wwwroot/video
添加 Deploy Key 后的验证
公钥添加到 Git 平台后,在服务器执行:
cd /www/wwwroot/video
git fetch origin
git pull origin master
能正常拉取说明密钥和 config 都配置正确。
小结
- 每个项目/仓库用独立密钥,互不影响
- 公钥只给 Deploy keys,不要和服务器登录公钥混用
- 遇到
dubious ownership,加safe.directory即可 - 一键脚本:
tool/git-ssh-init/init-git-ssh.sh