ssh 免密码登录

通常的ssh登录有两种方式,一种是通过密码登录,一种是通过密钥登录,在实际使用过程中,会发现用密码登录很繁琐,需要每次都输入密码,这时候用密钥登录就会很方便。

密码登录

格式

1
2
$ ssh root@10.2.8.41
root@10.2.8.41's password:

这时候输入密码就可以登录成功

1
2
3
4
$ ssh root@10.2.8.41
root@10.2.8.41's password:
Last login: Thu Nov 1 11:34:05 2018 from 10.2.0.33
[root@hardwareupdate ~]#

密钥登录

创建密钥
1
2
3
4
5
6
7
8
9
10
[root@host ~]$ ssh-keygen -t rsa  <== 建立密钥对
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. <== 公钥
The key fingerprint is:
0f:d3:e7:1a:1c:bd:5c:03:f1:19:f1:22:df:9b:cc:08 root@host

密钥生成以后,在.ssh下面会多两个文件,id_rsa.pub是公钥,id_rsa是私钥

1
2
3
[root@host ~]$ cd ~/.ssh
[root@host .ssh]$ ls
id_rsa id_rsa.pub known_hosts config

然后把公钥上传到服务器上,scp等同于ssh-copy-id -i

1
2
3
[root@A ~]# scp /root/.ssh/id_rsa.pub root@192.168.1.181:/root/.ssh/authorized_keys  
root@192.168.1.181's password:
id_rsa.pub 100% 223 0.2KB/s 00:00

由于还没有免密码登录的,所以要输入一次服务器的密码登录,如果服务器没有authorized_keys文件,用touch authorized_keys 创建

服务器

登录服务器,进入.ssh里面,给authorized_keys设置权限

1
2
3
4
[root@host ~]$ cd ~/.ssh
[root@host .ssh]$ ls
authorized_keys known_hosts
[root@host .ssh]$ chmod 600 authorized_keys
本地配置权限
1
2
[root@host ~]$ cd ~/.ssh
[root@host .ssh]$ chmod 600 id_rsa

这时候就可以用密钥登录了

1
ssh -i ~/.ssh/id_rsa root@192.168.100.39

用config去管理

ssh -i ~/.ssh/id_rsa root@192.168.100.39登录时很繁琐的,这时候就可以用config去管理

例如

1
2
3
4
5
6
7
8
9
10
11
12
# ~/.ssh/config 文件示例
# Host 参数标明以下内容仅适用于访问 236 主机时适用,Host 参数本身只是一个入口字符串;
Host fuwuqi
  HostName 192.168.99.236
  User git
  Port 22
  IdentityFile ~/.ssh/rsa-michael-236
Host github
  HostName 192.168.99.3
  User root
  Port 22
  IdentityFile ~/.ssh/rsa-3root-michael

配置完这些以后,就可以用这个登录了

1
2
3
[root@host ~] ssh fuwuqi
Last login: Thu Nov 8 09:40:00 2018 from 192.168.99.236
Welcome to Alibaba Cloud Elastic Compute Service !