0%

ssh免密登录

概述

管理多台阿里云服务器的情况下,每登录一台都输入一遍密码实在太麻烦。

所以我这里使用了ssh的相关命令,来实现在git.huluwa.cc和www.liumapp.com这两台服务器上的免密登录。

为了不影响我原来所使用在Github上的密钥,我创建了两个新的密钥用于登录服务器。

生成证书

首先进入/var/root/.ssh目录,可以看到,我已经具有一个密钥:

id_rsa  id_rsa.pub  known_hosts

现在我使用ssh-keygen命令创建一个新的密钥id_rsa_test,用于登录git.huluwa.cc:

sh-3.2# ssh-keygen

Generating public/private rsa key pair.

Enter file in which to save the key (/var/root/.ssh/id_rsa): /var/root/.ssh/id_rsa_test

Enter passphrase (empty for no passphrase): 

Enter same passphrase again: 

Your identification has been saved in /var/root/.ssh/id_rsa_test.

Your public key has been saved in /var/root/.ssh/id_rsa_test.pub.

The key fingerprint is:

SHA256:UHj31HSPlaw/DgWU8Gro7PGByE2wtaJa7/m56gDtsE4 root@liumeishengqideMacBook-Pro.local

The key's randomart image is:

+---[RSA 2048]----+

|  .. .o++ +|

| ... . oo.*.|

| .o o o .+ .|

| . .+ o o. . |

|  o . oS+ o o |

| = o B o . o |

|  E = o * . o .|

| o o o o + . . |

|  o o*o=..  |

+----[SHA256]-----+

再使用同样的方法,创建一个新的密钥id_rsa_liumapp用于登录www.liumapp.com

使用ssh-agent

直接在命令行输入:

ssh-agent

以启动ssh-agent:

sh-3.2# ssh-agent

SSH_AUTH_SOCK=/tmp/ssh-zuRqtql3yn1F/agent.21608; export SSH_AUTH_SOCK;

SSH_AGENT_PID=21609; export SSH_AGENT_PID;

echo Agent pid 21609;

再使用ssh-add,将id_rsa、id_rsa_test、id_rsa_liumapp添加到ssh列表中:

sh-3.2# ssh-add

Identity added: /var/root/.ssh/id_rsa (/var/root/.ssh/id_rsa)

sh-3.2# ssh-add /var/root/.ssh/id_rsa_test

Identity added: /var/root/.ssh/id_rsa_test (/var/root/.ssh/id_rsa_test)

使用ssh-copy-id

接下来使用ssh-copy-id这个命令,将公钥上传到要登录的服务器上,但是不知道为什么,我的Mac环境没有自带ssh-copy-id,使用命令:

brew install ssh-copy-id

进行安装:

sh-3.2# brew install ssh-copy-id

**==>** **Downloading http://ftp.openbsd.org/pub/OpenBSD/OpenSSH/portable/openssh-7.1p1.tar.gz**

######################################################################## 100.0%

/usr/local/Cellar/ssh-copy-id/7.1p1: 7 files, 334.3K, built in 10 seconds

接下来把公钥id_rsa_test.pub上传到git.huluwa.cc上:

ssh-copy-id -i /var/root/.ssh/id_rsa_test.pub git.huluwa.cc

成功的话可以看到这个结果:

sh-3.2# ssh-copy-id -i /var/root/.ssh/id_rsa_test.pub git.huluwa.cc

/usr/local/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed

/usr/local/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys

root@git.huluwa.cc's password: 

/etc/profile.d/lang.sh: line 19: warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such file or directory

Number of key(s) added: 1

Now try logging into the machine, with:  "ssh 'git.huluwa.cc'"

and check to make sure that only the key(s) you wanted were added.

最后使用

ssh git.huluwa.cc    

就可以成功免密登录到服务器上了,同理,对于id_rsa_liumapp.pub进行同样的操作即可免密登录到www.liumapp.com上。

注意事项

  • 在实践过程中,我发现如果用IP地址代替域名,那么最后登录的时候,还是需要验证密码,不过暂时还没有发现原因出在哪里。

  • 如果说电脑重启过,那么需要重新走一遍ssh-agent和ssh-add操作,推荐大家使用shell来自动化解决…