Skip to content

私钥公钥使用别再搞混了! ​

1. GitHub 仓库访问密钥对 ​

这是用于您的电脑与 GitHub 之间的通信。

用途:让您能够从本地推送代码到 GitHub 而不需要输入密码

查看现有密钥:

sh
# 查看是否已有 GitHub 相关的 SSH 密钥
ls -la ~/.ssh/
# 常见的 GitHub 密钥名称:
# - id_rsa (私钥)
# - id_rsa.pub (公钥)

生成新密钥:

bash
ssh-keygen -t rsa -b 4096 -C "your_github_email@example.com"
# 建议使用默认路径 (~/.ssh/id_rsa)

配置到 GitHub:

  1. 复制公钥内容:
bash
cat ~/.ssh/id_rsa.pub
  1. 在 GitHub.com -> Settings -> SSH and GPG keys -> New SSH key
  2. 粘贴公钥内容

2. 服务器部署密钥对 ​

这是用于 GitHub Actions 自动部署代码到您的服务器。

用途:让 GitHub Actions 能够自动将构建后的文件部署到您的服务器

1. 生成专用的部署密钥:

bash
# 建议生成一个专门用于部署的密钥对,使用不同的文件名
ssh-keygen -t rsa -b 4096 -C "deploy_key" -f ~/.ssh/deploy_key

2. 执行命令后会提示:

  1. 输入密码短语(建议直接回车,不设置密码,否则自动部署时会出问题)
  2. 确认密码短语(再次回车) 然后就会在指定位置生成两个文件:
  • 私钥文件:imgprocessing_key
  • 公钥文件:imgprocessing_key.pub

3. 确认密钥已生成:

bash
ls -la ~/.ssh/imgprocessing_key*
# 应该看到两个文件:
# imgprocessing_key
# imgprocessing_key.pub

4. 设置正确的权限:

bash
chmod 600 ~/.ssh/imgprocessing_key
chmod 644 ~/.ssh/imgprocessing_key.pub

5. 配置到服务器:

  1. 查看公钥内容(这个需要添加到服务器):
bash
cat ~/.ssh/imgprocessing_key.pub
  1. 查看私钥内容(这个需要添加到 GitHub Secrets):
bash
cat ~/.ssh/imgprocessing_key
  1. 将公钥添加到服务器:
bash
# 方法1:使用 ssh-copy-id
ssh-copy-id -i ~/.ssh/deploy_key.pub username@your_server_ip
# 测试连接
ssh -i ~/.ssh/imgprocessing_key username@your_server_ip

# 方法2:手动添加
cat ~/.ssh/deploy_key.pub | ssh username@your_server_ip "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

6. 配置到 GitHub Actions:

  1. 查看私钥内容:
bash
cat ~/.ssh/deploy_key
  1. 在 GitHub 仓库 -> Settings -> Secrets -> Actions -> New repository secret
  2. 添加以下 secrets:
SSH_PRIVATE_KEY: [deploy_key 私钥内容]
SSH_HOST: [您的服务器 IP]
SSH_USERNAME: [您的服务器用户名]