第一步: 产生公钥与私钥对:

[root@local-host]# ssh-keygen -t rsa

按照提示输入完后,会在~/.ssh目录下生成id_rsa和id_rsa.pub这两个文件

第二步:用ssh-copy-id将公钥复制到远程机器中

ssh-copy-id 将本机的公钥复制到远程机器的authorized_keys文件中,ssh-copy-id也会给远程主机的用户主目录(home)和 ~./ssh  和 ~/.ssh/authorized_keys设置合适的权利。

语法:

  ssh-copy-id [-i [identity_file]] [user@]machine

选项:

  -i:指定公钥文件

实例:

把本地的ssh公钥文件安装到远程主机对应的账户下:

[root@local-host]# ssh-copy-id -i ~/.ssh/id_rsa.pub remote-host

    root@remote-host's password:      #输入远程主机的用户密码
    Now try logging into the machine, with "ssh 'remote-host'", and check in:

      .ssh/authorized_keys

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

第三步: 登录到远程机器不用输入密码

[root@local-host]# ssh remote-host
Last login: Mon Sep 11 18:30:00 2017 from remote-host

常见问题:

[root@local-host]# ssh-copy-id -u demo -i ~demo/.ssh/id_rsa.pub demo@remote_host
/usr/bin/ssh-copy-id: ERROR: No identities found

上述是给demo用户赋予无密码登陆的权利

使用选项 -i ,当没有值传递的时候或者 如果 ~/.ssh/identity.pub 文件不可访问(不存在), ssh-copy-id 将显示上述的错误信息  ( -i选项会优先使用将ssh-add -L的内容)

[root@local-host]# ssh-agent $SHELL


[root@local-host]# ssh-add -L

The agent has no identities.



[root@local-host]# ssh-add

Identity added: /home/demo/.ssh/id_rsa (/home/demo/.ssh/id_rsa)



[root@local-host]# ssh-add -L

ssh-rsa AAAAB3NUaC1TR2SJKAABIwAAAQEAsJIEILuftj8aSxMa3k8t6JvM79DpBV

aHreqPShTYp7kISDMUNzUpnyxsHpH1tQ/Ow== /home/demo/.ssh/id_rsa



[root@local-host]# ssh-copy-id -i remote-host

demo@remote-host's password:

Now try logging into the machine, with "ssh 'remote-host'", and check in:



.ssh/authorized_keys



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

[Note: This has added the key displayed by ssh-add -L]