服务器设置 SSH 通过密钥登录,不用每次输入密码了,更加方便和安全。
制作密钥对
# 来自 https://hyjk2000.github.io/2012/03/16/how-to-set-up-ssh-keys/
[root@host ~]$ ssh-keygen <== 建立密钥对
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): <== 按 Enter
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase): <== 输入密钥锁码,或直接按 Enter 留空
Enter same passphrase again: <== 再输入一遍密钥锁码
Your identification has been saved in /root/.ssh/id_rsa. <== 私钥
Your public key has been saved in /root/.ssh/id_rsa.pub. <== 公钥
在 root 用户的家目录中生成了一个 .ssh 的隐藏目录,内含两个密钥文件。id_rsa 为私钥,id_rsa.pub 为公钥。
在服务器上安装公钥
cd .ssh
cat id_rsa.pub >> authorized_keys
chmod 600 authorized_keys
chmod 700 ~/.ssh
设置 SSH,打开密钥登录功能
# 编辑 /etc/ssh/sshd_config 文件
RSAAuthentication yes
PubkeyAuthentication yes
PermitRootLogin yes # root 用户能否通过 SSH 登录
【可选】禁用密码登录
# PasswordAuthentication no
重启 SSH 服务
service sshd restart
复制私钥到 Mac 上
# 1、把服务器上 /root/.ssh/id_rsa 这个文件下载下来
# 2、然后把 id_rsa 放到 Mac 的 ~/.ssh/ 目录下
Mac 私钥权限安全报错
admin@Macintoshssh -p 2222 [email protected]
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: UNPROTECTED PRIVATE KEY FILE! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for '/Users/admin/.ssh/id_rsa' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key"/Users/admin/.ssh/id_rsa": bad permissions
[email protected]'s password:
Permission denied, please try again.
限制私钥权限
chmod 400 ~/.ssh/id_rsa