在Ubuntu上配置SSH密钥登录的完整步骤:

1. 生成SSH密钥对

在客户端机器上(你要用来连接的机器):

  1. # 生成RSA密钥对(推荐4096位)
  2. ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
  3. # 或者生成Ed25519密钥(更安全,推荐)
  4. ssh-keygen -t ed25519 -C "your_email@example.com"

按提示操作:

  • 选择密钥保存位置(默认:~/.ssh/id_rsa
  • 设置密码短语(可选,但推荐)

2. 将公钥复制到服务器

方法一:使用ssh-copy-id(推荐)

  1. ssh-copy-id username@server_ip

方法二:手动复制

  1. # 查看公钥内容
  2. cat ~/.ssh/id_rsa.pub
  3. # 登录服务器后,将公钥内容添加到authorized_keys
  4. mkdir -p ~/.ssh
  5. echo "公钥内容" >> ~/.ssh/authorized_keys
  6. chmod 700 ~/.ssh
  7. chmod 600 ~/.ssh/authorized_keys

方法三:使用scp复制

  1. scp ~/.ssh/id_rsa.pub username@server_ip:~/
  2. # 登录服务器后
  3. cat ~/id_rsa.pub >> ~/.ssh/authorized_keys
  4. rm ~/id_rsa.pub

3. 配置SSH服务器(在Ubuntu服务器上)

编辑SSH配置文件:

  1. sudo nano /etc/ssh/sshd_config

确保以下配置正确:

  1. # 启用公钥认证
  2. PubkeyAuthentication yes
  3. # 指定authorized_keys文件位置
  4. AuthorizedKeysFile .ssh/authorized_keys
  5. # 可选:禁用密码登录(提高安全性)
  6. PasswordAuthentication no
  7. # 可选:禁用root登录
  8. PermitRootLogin no
  9. # 可选:只允许特定用户登录
  10. AllowUsers username1 username2

注意:此处的文件是sshd_config,而不是ssh_config;同时,要把文件开头的“Include /etc/ssh/sshd_config.d/*.conf”语句注释,因为这个导入的配置文件里默认是开启密码登录的,这会导致你后续配置的密钥登录无效

重启SSH服务:

  1. sudo systemctl restart sshd

注意:此处重启的服务是sshd,而不是ssh

4. 测试密钥登录

  1. # 从客户端测试连接
  2. ssh username@server_ip
  3. # 指定密钥文件(如果不是默认位置)
  4. ssh -i ~/.ssh/your_private_key username@server_ip

5. 创建SSH配置文件(可选)

在客户端创建 ~/.ssh/config 文件来简化连接:

  1. nano ~/.ssh/config

添加配置:

  1. Host myserver
  2. HostName server_ip
  3. User username
  4. Port 22
  5. IdentityFile ~/.ssh/id_rsa
  6. IdentitiesOnly yes

然后可以直接使用:

  1. ssh myserver

6. 安全建议

  1. 设置正确的文件权限

    1. chmod 700 ~/.ssh
    2. chmod 600 ~/.ssh/id_rsa
    3. chmod 644 ~/.ssh/id_rsa.pub
    4. chmod 600 ~/.ssh/authorized_keys
    5. chmod 600 ~/.ssh/config
  2. 备份私钥并安全保存

  3. 考虑使用SSH Agent: ```bash

    启动ssh-agent

    eval “$(ssh-agent -s)”

添加私钥

ssh-add ~/.ssh/id_rsa

  1. 4. **定期更换密钥**
  2. 5. **监控SSH日志**:
  3. ```bash
  4. sudo tail -f /var/log/auth.log

配置完成后,你就可以使用密钥安全地登录Ubuntu服务器,无需输入密码了。