git配置遇到的问题

问题1:SSH密钥配置问题

问题描述:
执行 git clone git@github.com:... 时出现错误:

1
fatal: Could not read from remote repository.

原因:
GitHub 账户未配置 SSH 密钥,无法进行身份验证。

解决方案:
请参考:GitHub SSH 密钥配置教程

问题2:Hexo 部署失败

问题描述:
执行 hexo d 命令时出现 spawn failed 错误,导致无法部署到 GitHub。

解决方案:

  1. 删除博客根目录下的 .deploy_git 文件夹
  2. 配置 Git 换行符处理方式:
    1
    git config --global core.autocrlf false

    注意:建议使用 Git Bash 而非 CMD 执行以上命令

  3. 重新执行部署命令:
    1
    2
    3
    hexo clean
    hexo generate
    hexo deploy

参考资料:Hexo部署问题解决方案

问题3:Git 仓库单独配置

问题描述:
在实验室服务器上,由于所有人共用同一个账户(这不是一个好的做法),且全局的 .ssh 已被其他人配置,因此需要为特定仓库单独配置 Git:

解决方案:

首先是创建一个本地的git仓库

1
git init

之后在该仓库配置git账户

1
2
git config user.name "New User Name"
git config user.email "new.email@example.com"

查看该仓库的配置

1
git config --list

设置RSA密钥

1
2
3
4
5
6
7
8
9
ssh-keygen \
-t rsa # 指定密钥类型为 RSA
-b 4096 # 设置密钥长度为 4096 位,RSA 密钥的安全性依赖于其位数(长度)。位数越长,破解难度呈指数级增加。default: 2048
-C "new.email@example.com" # 添加注释(通常用于标识密钥用途)
-f folder/id_rsa_new # 指定密钥文件名(私钥 `id_rsa_new` 和公钥 `id_rsa_new.pub`)folder为绝对路径
# 具体示例如下
ssh-keygen -t rsa -b 4096 -C "new.email@example.com" -f ~/.ssh/id_rsa_new
# 设置私钥权限
chmod 600 ~/.ssh/id_rsa_new

远程配置

复制以上id_rsa_new.pub的内容
登录到 GitHub,进入 Settings -> SSH and GPG keys,点击 New SSH key,将复制的公钥粘贴进去。

测试连接

1
2
3
4
ssh \
-i \ # 指定私钥文件路径
-T \ # 禁止分配伪终端(仅测试连接)
git@github.com # 连接目标服务器(GitHub)

指定当前仓库的ssh路径

方法一

1
git config core.sshCommand "ssh -i folder/id_rsa_new"

测试连接:

1
ssh -T git@github.com-wjh

方法二

~/.ssh/config 文件中添加规则,为特定仓库域名或 URL 指定密钥。例如:

1
2
3
4
5
6
# ~/.ssh/config
Host github.com-new # 自定义别名(可任意命名)
HostName github.com # 实际连接的域名
User git # Git 协议使用的用户名
IdentityFile folder/id_rsa_new # 指定私钥路径
IdentitiesOnly yes # 仅使用此密钥(避免尝试其他密钥)

之后使用
1
git remote set-url origin git@github.com-new:your-username/your-repo.git

来远程配置。

远程管理

添加远程仓库:

1
2
# 添加远程仓库并命名为 origin(可自定义其他名称)
git remote add origin git@github.com:your-username/new-repo.git

推送:
1
2
3
4
# 添加远程仓库并命名为 origin(可自定义其他名称)
git remote add origin git@github.com:your-username/new-repo.git
# 若分支名不同 本地是 `master`,远程是 `main`
git push -u origin master:main

验证关联状态:
1
2
git remote -v
git branch -vv

若远程仓库非空,先拉取内容再推送:
1
2
git pull origin main --allow-unrelated-histories
git push origin main

参考资料:

Author

LLLLAAAA

Posted on

2025-02-03

Updated on

2025-02-20

Licensed under

Comments