使用指定private key连接git

本文介绍如何通过SSH密钥进行身份验证,并配置Git远程仓库。主要内容包括修改SSH配置文件config,设置gitconfig文件中的用户信息,以及如何添加远程仓库origin。适用于需要通过SSH连接GitHub或其他Git仓库系统的用户。
1. 修改config
Host 优快云BlogDownloader
  HostName    github.com
  IdentityFile    ~/.ssh/geurneyma_rsa
  IdentitiesOnly yes
  User git
  
2. git config user.name "优快云BlogDownloader" 
   git config user.gmail "geurneyma@gmail.com"
   修改repo的git配置

3. git remote add origin git@优快云BlogDownloader:优快云BlogDownloader/优快云BlogDownloader.git
  @后跟的是上面的Host,:后跟的是github的用户名
  或者

  git clone git@优快云BlogDownloader:优快云BlogDownloader/优快云BlogDownloader.git 优快云BlogDownloader



要“连接 Git 仓库”,通常是指在本地或 CI/CD 环境中配置并建立与远程 Git 仓库(如 GitHub、GitLab、Gitee、Azure DevOps 等)的安全通信,以便进行代码拉取(clone)、推送(push)或持续集成操作。 --- ### ✅ 连接 Git 仓库的基本步骤 #### 1. **安装 Git** 确保系统已安装 Git: ```bash # Linux (Ubuntu/Debian) sudo apt update && sudo apt install git -y # macOS brew install git # Windows # 下载并安装:https://git-scm.com/download/win ``` 验证安装: ```bash git --version ``` --- #### 2. **配置用户信息** ```bash git config --global user.name "YourName" git config --global user.email "your.email@example.com" ``` > 注意:CI/CD 中可不设全局配置,而在命令中临时指定。 --- #### 3. **选择认证方式(关键)** ##### ✅ 方式一:SSH 密钥认证(推荐) **优点**:安全、免密、适合自动化。 ###### 步骤: 1. 生成 SSH 密钥对(如果还没有): ```bash ssh-keygen -t ed25519 -C "your.email@example.com" -f ~/.ssh/id_ed25519 ``` 2. 将公钥(`~/.ssh/id_ed25519.pub`)内容添加到 Git 平台: - GitHub: `Settings → SSH and GPG keys` - GitLab: `Preferences → SSH Keys` - Gitee: `设置 → 安全设置 → SSH 公钥` 3. 测试连接: ```bash ssh -T git@github.com # 或 ssh -T git@gitlab.com ``` 4. 使用 SSH 地址克隆仓库: ```bash git clone git@github.com:username/repo.git ``` --- ##### ✅ 方式二:Personal Access Token (PAT) + HTTPS **适用场景**:无法使用 SSH(如某些企业代理环境)。 ###### 步骤: 1. 在平台生成 PAT(权限建议:`repo` 范围)。 2. 克隆时使用令牌作为密码: ```bash git clone https://github.com/username/repo.git # 输入用户名,密码填 PAT ``` 3. 或直接嵌入 URL(谨慎用于脚本): ```bash git clone https://<TOKEN>@github.com/username/repo.git ``` > ⚠️ 安全提示:避免硬编码 token,应使用环境变量或 Git 凭证管理器。 --- #### 4. **克隆仓库** ```bash git clone git@github.com:username/repo.git cd repo ``` 可指定分支: ```bash git clone -b main git@github.com:username/repo.git ``` --- #### 5. **在 CI/CD 中自动连接(示例:GitHub Actions)** ```yaml - name: Checkout Code uses: actions/checkout@v4 with: ssh-key: ${{ secrets.SSH_PRIVATE_KEY }} ``` 或使用 token: ```yaml - name: Checkout uses: actions/checkout@v4 ``` --- ### 🔐 常见问题解决 | 问题 | 解决方法 | |------|----------| | `Permission denied (publickey)` | 检查 SSH 密钥是否加载:`ssh-add -l` | | `Host key verification failed` | 删除旧记录:`ssh-keygen -R github.com` | | `fatal: could not read Username` | HTTPS 方式未提供凭证,改用 PAT 或 SSH | --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值