ssh-copy-id
命令笔记
1. 命令简介
ssh-copy-id
是一个用于将本地 SSH 公钥自动添加到远程服务器 authorized_keys
文件的工具,实现免密 SSH 登录。
2. 基本语法
ssh-copy-id [-i [identity_file]] [user@]hostname
3. 常用选项
选项 | 说明 |
---|---|
-i [identity_file] |
指定公钥文件(默认:~/.ssh/id_rsa.pub ) |
-p port |
指定 SSH 端口(非默认 22 端口时使用) |
-f |
强制模式,不检查密钥是否已存在 |
-n |
只打印命令而不执行 |
-o ssh_option |
传递其他 SSH 选项 |
4. 使用示例
4.1 基本使用
ssh-copy-id user@192.168.1.100
4.2 指定公钥文件
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@host
4.3 指定非标准端口
ssh-copy-id -p 2222 user@host
4.4 组合使用
ssh-copy-id -i ~/.ssh/work_key.pub -p 2222 user@work-server
5. 工作原理
- 检查本地公钥文件
- 通过 SSH 连接到目标服务器
- 将公钥追加到
~/.ssh/authorized_keys
- 设置正确的文件权限:
~/.ssh
→ 700~/.ssh/authorized_keys
→ 600
6. 手动替代方案
当 ssh-copy-id
不可用时:
cat ~/.ssh/id_rsa.pub | ssh user@host "mkdir -p ~/.ssh &&
cat >> ~/.ssh/authorized_keys &&
chmod 700 ~/.ssh &&
chmod 600 ~/.ssh/authorized_keys"
7. 验证配置
ssh user@host
成功则无需输入密码直接登录
8. 注意事项
- 确保已生成密钥对:
ssh-keygen
- 首次连接需确认主机指纹
- 检查远程服务器文件权限:
chmod 700 ~/.ssh chmod 600 ~/.ssh/authorized_keys
- 某些系统需在
/etc/ssh/sshd_config
中启用:PubkeyAuthentication yes
9. 故障排查
- 权限问题:
ssh -v user@host # 查看详细错误
- 服务端配置:
检查/var/log/secure
或/var/log/auth.log
10. 扩展知识
- 生成新密钥:
ssh-keygen -t ed25519
- 查看公钥:
cat ~/.ssh/id_ed25519.pub
- 禁用密码登录(安全建议):
# 在 /etc/ssh/sshd_config 中设置: PasswordAuthentication no
已有 0 条评论