用密码登录SSH好不方便,并且安全性不高,为了提升安全性那我们就用密钥登录.
本地环境:OS X,估计是Linux就可以.
1.在远程服务器上创建密钥对.
# create key pair
[cent@dlp ~]$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/cent/.ssh/id_rsa): # 路径默认,直接回车
Created directory '/home/cent/.ssh'.
Enter passphrase (empty for no passphrase): # 设置密钥密码,直接回车,不用设置
Enter same passphrase again:#再次输入密码,直接回车
Your identification has been saved in /home/cent/.ssh/id_rsa.
Your public key has been saved in /home/cent/.ssh/id_rsa.pub.
The key fingerprint is:
38:f1:a4:6d:d3:0e:99:c8:fa:1d:1d:48:86:f0:fe:74 cent@dlp.server.world
The key's randomart image is:
[cent@dlp ~]$ mv ~/.ssh/id_rsa.pub ~/.ssh/authorized_keys#将id_rsa.pub中的公钥复制到authorized_keys中
[cent@dlp ~]$ chmod 600 ~/.ssh/authorized_keys #修改authorized_keys权限为拥有者可读写
2.将远程服务器上的私钥下载到本地用于登录远程服务器
以下是本地操作
[cent@www ~]$ mkdir ~/.ssh #创建文件夹
[cent@www ~]$ chmod 700 ~/.ssh #修改文件夹权限为拥有者可'读,写,执行'
# copy the secret key to local ssh directory
[cent@www ~]$ scp cent@10.0.0.30:/home/cent/.ssh/id_rsa ~/.ssh/ #将远程的私钥下载到本地,这要注意路径,如果用root登录的,路径是:/root/.ssh/id_rsa
cent@10.0.0.30's password: #输入远程服务器密码
id_rsa
[cent@www ~]$ ssh -i ~/.ssh/id_rsa cent@10.0.0.30 #现在就可以用这条命令登录远程服务器了
Enter passphrase for key '/home/cent/.ssh/id_rsa': # 刚才密钥没设置密码,所以不会出现
Last login: Wed Jul 30 21:37:19 2014 from www.server.world
[cent@dlp ~]$ # 登录成功
3.简化登录
本地机器执行下面代码:
vi ~/.ssh/config
加入下面一段内容:
Host server #别名,域名缩写
HostName jingxuetao.com #完整的域名
User root #登录该域名使用的账号名
PreferredAuthentications publickey #加不加都一样,SSH会优先密钥登录
IdentityFile ~/.ssh/id_rsa #私钥文件的路径
#删掉#号后面的中文,包括这句
上面配置完了之后就可以通过ssh server
或者ssh jingxuetao.com
来登录远程服务器了.
4.关闭密码验证登录
操作远程服务器
vi /etc/ssh/sshd_config
找到PasswordAuthentication
将其值改为no
PasswordAuthentication no
最后用systemctl restart sshd
或者service sshd restart
重启SSH服务
好了,sshd_config文件中除了配置PasswordAuthentication这条之外其他的并不用配置,还是被注释状态
保存到本地的密钥,最好备份到网盘一份.
本文参考:server-world
本人博客:上善若水 欢迎访问_.
--EOF--