天天看點

SSH 免密碼登入

轉載:http://www.jb51.net/article/94599.htm

1.Linux下生成密鑰

  ssh-keygen的指令手冊,通過”man ssh-keygen“指令:

SSH 免密碼登入

  通過指令”ssh-keygen -t rsa“

SSH 免密碼登入

  生成之後會在使用者的根目錄生成一個 “.ssh”的檔案夾

SSH 免密碼登入

  進入“.ssh”會生成以下幾個檔案

SSH 免密碼登入

authorized_keys:存放遠端免密登入的公鑰,主要通過這個檔案記錄多台機器的公鑰

id_rsa : 生成的私鑰檔案

id_rsa.pub : 生成的公鑰檔案

  know_hosts : 已知的主機公鑰清單

    如果希望ssh公鑰生效需滿足至少下面兩個條件:

1) .ssh目錄的權限必須是700 

     2) .ssh/authorized_keys檔案權限必須是600

2.遠端免密登入

  原理圖:

SSH 免密碼登入
  常用以下幾種方法:  2.1 通過ssh-copy-id的方式

指令: ssh-copy-id -i ~/.ssh/id_rsa.put

    舉例:

?

1

2

3

4

5

6

7

8

9

10

11

[[email protected]]# ssh-copy-id -i ~/.ssh/id_rsa.pub 192.168.91.135

[email protected]'s password:

Now try logging into the machine, with "ssh '192.168.91.135'", and check in:

.ssh/authorized_keys

to makesure we haven't added extra keys that you weren't expecting.

[[email protected]]# ssh [email protected]

Last login: Mon Oct 10 01:25:49 2016 from 192.168.91.133

[root@localhost ~]#

    常見錯誤:

      [root@test ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub 192.168.91.135

      -bash: ssh-copy-id: command not found //提示指令不存在

解決辦法:yum -y install openssh-clients

   2.2 通過scp将内容寫到對方的檔案中

指令:scp -p ~/.ssh/id_rsa.pub root@:/root/.ssh/authorized_keys

      舉例:

[[email protected]]# scp -p ~/.ssh/id_rsa.pub [email protected]:/root/.ssh/authorized_keys

id_rsa.pub 100% 408 0.4KB/s00:00

[[email protected]]#

Last login: Mon Oct 10 01:27:02 2016 from 192.168.91.133

也可以分為兩步操作:

$ scp ~/.ssh/id_rsa.pub root@:pub_key //将檔案拷貝至遠端伺服器

$ cat ~/pub_key >>~/.ssh/authorized_keys //将内容追加到authorized_keys檔案中, 不過要登入遠端伺服器來執行這條指令

2.3 通過Ansible實作批量免密 2.3.1 将需要做免密操作的機器hosts添加到/etc/ansible/hosts下:

[Avoid close]

192.168.91.132

192.168.91.133

192.168.91.134

2.3.2 執行指令進行免密操作

  ansible -m authorized_key -a "user=root key='{{ lookup('file','/root/.ssh/id_rsa.pub') }}'" -k

示例:

12

13

14

[[email protected]]# ansible test -m authorized_key -a "user=root key='{{ lookup('file','/root/.ssh/id_rsa.pub') }}'" -k

  SSH password: ----->輸入密碼

  192.168.91.135 | success >> {

  "changed": true,

  "key": "ssh-rsa    AAAAB3NzaC1yc2EAAAABIwAAAQEArZI4kxlYuw7j1nt5ueIpTPWfGBJoZ8Mb02OJHR8yGW7A3izwT3/uhkK7RkaGavBbAlprp5bxp3i0TyNxa/apBQG5NiqhYO8YCuiGYGsQAGwZCBlNLF3gq1/18B6FV5moE/8yTbFA4dBQahdtVP PejLlSAbb5ZoGK8AtLlcRq49IENoXB99tnFVn3gMM0aX24ido1ZF9RfRWzfYF7bVsLsrIiMPmVNe5KaGL9kZ0svzoZ708yjWQQCEYWp0m+sODbtGPC34HMGAHjFlsC/SJffLuT/ug/hhCJUYeExHIkJF8OyvfC6DeF7ArI6zdKER7D8M0SM  WQmpKUltj2nltuv3w== [email protected]",

  "key_options": null,

  "keyfile": "/root/.ssh/authorized_keys",

  "manage_dir": true,

  "path": null,

  "state": "present",

  "unique": false,

  "user": "root"

  }

  [[email protected]]#

2.4 手工複制粘貼的方式

  将本地id_rsa.pub檔案的内容拷貝至遠端伺服器的~/.ssh/authorized_keys檔案中