云服务器配置指南 (二):Git 与 SSH 的正确打开方式

代码是程序员的生命,Git 就是代码的保险箱。

在服务器上配好 Git,不仅是为了拉代码,更是为了让你的部署流程像丝般顺滑。试想一下,本地 git push,服务器自动拉取更新,这才是现代开发的节奏。

本章我们来聊聊如何在服务器上优雅地配置 Git,特别是如何搞定那个让人头大的 SSH 连接。


2.1 Git 安装与基础配置

为什么服务器必须有 Git?

服务器上没 Git,就像吃饭没筷子。

  • 拉代码:这是最基本的。
  • 改配置:服务器上的配置文件用 Git 管理起来,改错了随时回滚,谁用谁知道。
  • 自动化:CI/CD 的基石。

步骤1:安装 Git

Ubuntu 下一条命令搞定:

1
2
sudo apt update
sudo apt install git -y

验证一下:

1
git --version

步骤2:自报家门

告诉 Git 你是谁。虽然在服务器上我们通常只拉取代码,但偶尔也会在服务器上临时改点东西提交(虽然不推荐),这时候没有用户信息会报错。

1
2
git config --global user.name "Your Name"
git config --global user.email "your_email@example.com"

步骤3:一些让你舒服的配置

1
2
3
4
5
6
7
8
# 默认编辑器设为 vim(除非你喜欢 nano)
git config --global core.editor "vim"

# 默认分支名设为 main(跟上时代的步伐)
git config --global init.defaultBranch main

# 记住密码(如果你非要用 HTTPS 的话,虽然我强烈反对)
# git config --global credential.helper store

2.2 SSH 密钥:给 GitHub/GitLab 发张通行证

为什么不用 HTTPS?

HTTPS 每次都要输账号密码(或者 Token),烦不烦?
SSH 配置一次,终身免密。而且在服务器这种自动化场景下,SSH 是唯一的选择。

步骤1:生成专用密钥

注意:我建议给服务器生成一个专用的密钥,不要和本地电脑混用,也不要和服务器登录的密钥混用。这样万一服务器被黑,你只需要在 GitHub 上把这个密钥删了就行,不影响其他地方。

1
2
# 生成一个专门给 GitHub 用的密钥
ssh-keygen -t ed25519 -C "server_github_key" -f ~/.ssh/id_ed25519_github

一路回车,不要设密码短语!服务器上的自动化脚本是没法帮你输密码的。

步骤2:配置 SSH Config

这是很多人忽略的一步。通过 ~/.ssh/config 文件,我们可以管理多个密钥,让 SSH 知道连 GitHub 时该用哪把钥匙。

1
vim ~/.ssh/config

写入:

1
2
3
4
5
6
7
8
9
10
11
12
# GitHub
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_github
PreferredAuthentications publickey

# GitLab (如果你用的话)
Host gitlab.com
HostName gitlab.com
User git
IdentityFile ~/.ssh/id_ed25519_gitlab

别忘了设置权限,SSH 对权限很敏感:

1
chmod 600 ~/.ssh/config

步骤3:把公钥告诉 GitHub

  1. 查看公钥内容:
    1
    cat ~/.ssh/id_ed25519_github.pub
  2. 复制那一长串字符。
  3. 去 GitHub -> Settings -> SSH and GPG keys -> New SSH key
  4. 粘贴进去,起个名字叫 My Server

步骤4:见证奇迹的时刻

测试一下连接:

1
ssh -T git@github.com

如果看到 Hi username! You've successfully authenticated...,恭喜你,通了!

如果看到 Permission denied,检查一下公钥是不是粘错了,或者 ~/.ssh/config 权限对不对。

技巧:强制 Git 走 SSH

有时候我们手滑复制了 HTTPS 的链接,或者某些子模块用的是 HTTPS。我们可以让 Git 自动把 HTTPS 替换成 SSH:

1
git config --global url."git@github.com:".insteadOf "https://github.com/"

这样,即使你 git clone https://github.com/xxx/xxx.git,它也会自动走 SSH 通道。


2.3 常用操作速查

虽然大家都是老司机了,但有些命令在服务器上用得特别多:

  • 拉取最新代码
    1
    git pull origin main
  • 丢弃本地修改(慎用)
    有时候服务器上的文件被改乱了,想恢复到干净状态:
    1
    2
    git checkout .
    git clean -fd
  • 查看最近提交
    1
    git log --oneline -n 5

总结

配置好 Git 和 SSH,你的服务器就打通了任督二脉。代码想拉就拉,部署想发就发。

下一章,我们将解决另一个痛点:国内服务器下载速度慢的问题,教你如何配置系统镜像源。