在 Ubuntu 中配置 Git 的账号和密码(或身份验证信息),需根据使用场景选择 HTTPSSSH 协议,并结合全局/仓库级配置。以下是详细步骤:


一、配置全局用户名和邮箱

Git 要求每次提交关联开发者身份,需设置全局用户名和邮箱(推荐与 GitHub/GitLab 注册信息一致):

# 设置全局用户名(替换为你的名字)
git config --global user.name "YourName"

# 设置全局邮箱(替换为注册平台的邮箱)
git config --global user.email "email@example.com"
  • 验证配置
    git config user.name    # 查看用户名
    git config user.email   # 查看邮箱
    
  • 配置文件路径~/.gitconfig(全局配置)或项目目录下的 .git/config(仓库级配置)。

二、配置远程仓库地址(HTTPS 或 SSH)

根据仓库协议选择认证方式:

1. 使用 HTTPS 协议
  • 适用场景:需频繁切换账号或临时访问。

  • 配置步骤

    1. 修改远程仓库 URL:
      git remote set-url origin https://github.com/username/repo.git
      
    2. 首次推送时输入用户名和密码
      • GitHub 等平台已禁用密码登录,需使用 Personal Access Token (PAT) 替代密码。
      • 生成 PAT 后,在推送时输入即可。
  • 免密推送(缓存凭证)

    # 缓存密码 1 小时(临时)
    git config --global credential.helper 'cache --timeout=3600'
    
    # 永久明文存储(不推荐)
    git config --global credential.helper store
    
2. 使用 SSH 协议
  • 适用场景:长期固定账号,安全性更高。

  • 配置步骤

    1. 生成 SSH 密钥(若无):

      ssh-keygen -t ed25519 -C "email@example.com"  # 新版本 Git 推荐 ed25519
      

      按提示保存密钥(默认路径 ~/.ssh/id_ed25519),可设置密钥口令(可选)。

    2. 添加公钥到 Git 服务器

      • 复制公钥内容:cat ~/.ssh/id_ed25519.pub
      • 登录 GitHub/GitLab → Settings → SSH and GPG Keys → 添加新密钥。
    3. 修改远程仓库 URL

      git remote set-url origin git@github.com:username/repo.git
      
  • 测试 SSH 连接

    ssh -T git@github.com
    

    成功会显示 Hi <username>! You've successfully authenticated...


三、多账号管理(同时使用多个 Git 账号)

若需在同一设备管理多个 Git 账号(如工作与个人账号),需区分配置:

1. 基于 SSH 的多账号
  • 为每个账号生成独立密钥
    ssh-keygen -t ed25519 -C "work@email.com" -f ~/.ssh/id_ed25519_work
    ssh-keygen -t ed25519 -C "personal@email.com" -f ~/.ssh/id_ed25519_personal
    
  • 在 Git 服务器添加多个公钥
  • 配置 SSH 客户端~/.ssh/config):
    # 工作账号
    Host github-work
      HostName github.com
      User git
      IdentityFile ~/.ssh/id_ed25519_work
    
    # 个人账号
    Host github-personal
      HostName github.com
      User git
      IdentityFile ~/.ssh/id_ed25519_personal
    
  • 使用自定义 Host 克隆仓库
    git clone git@github-work:work-username/repo.git
    git clone git@github-personal:personal-username/repo.git
    
2. 基于 HTTPS 的多账号
  • 使用凭证助手区分账号
    # 为不同主机配置不同凭证
    git config --global credential.helper 'cache --timeout=3600'
    git config --local credential.helper 'store --file ~/.git-credentials-work'
    
  • 手动编辑凭证文件~/.git-credentials):
    # 工作账号
    https://work-username:work-password@github.com
    
    # 个人账号
    https://personal-username:personal-password@github.com
    

四、常见问题解决

  1. 推送时提示 403 Forbidden

    • 检查远程仓库 URL 是否为 HTTPS 或正确 SSH 地址。
    • 确保账号有仓库写入权限,或生成 PAT 替代密码。
  2. SSH 连接失败

    • 确认公钥已正确添加到 Git 服务器。
    • 检查私钥权限:chmod 600 ~/.ssh/id_ed25519
  3. 提交记录未关联账号

    • 检查全局/仓库级用户名和邮箱是否配置正确。
    • 修正历史提交:
      git commit --amend --author="Name <email@example.com>"
      

五、总结

  • 推荐协议:长期使用选 SSH(免密且安全),临时用 HTTPS + PAT
  • 多账号管理:SSH 通过自定义 Host 更简洁,HTTPS 需依赖凭证助手。
  • 安全建议:避免明文存储密码,优先使用 SSH 密钥或 PAT。
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐