boss$ ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/home/myself/.ssh/id_rsa): Enter passphrase (empty for no passphrase): <== 按下回车键即可 Enter same passphrase again: <== 按下回车键即可 Your identification has been saved in /home/myself/.ssh/id_rsa. Your public key has been saved in /home/myself/.ssh/id_rsa.pub. The key fingerprint is: SHA256:1zz6pZcMjA1av8iyojqo6NVYgTl1+cc+N43kIwGKOUI myself@boss The key's randomart image is: +---[RSA 3072]----+ | . .. | | E+ .. . | | .+ .o + o | | ..+.. .o* . | | ... So+*B o | | + ...==B . | | . o . ....++. | |o o . . o..o+ | |=..o.. ..o o. | +----[SHA256]-----+
上面显示的命令将创建公钥和私钥。其中公钥用于加密,私钥用于解密。因此,这些密钥之间的关系是关键的,私有密钥绝不应该被共享。相反,它应该保存在 boss 系统的 .ssh 文件夹中。
注意,在创建时,你的公钥和私钥将会保存在 .ssh 文件夹中。
下一步是将公钥复制到你希望从 boss 系统免密访问的系统。你可以使用 scp 命令来完成此操作,但此时你仍然需要输入密码。在本例中,该系统称为 “target”。
#!/bin/bash # NOTE: This script requires that you have the password for the remote acct # in order to set up password-free access using your public key
LOC=`hostname` # the local system from which you want to run commands from # wo a password
# get target system and account echo -n "target system> " read REM echo -n "target user> " read user
# create a key pair if no public key exists if [ ! -f ~/.ssh/id_rsa.pub ]; then ssh-keygen -t rsa fi
# ensure a .ssh directory exists in the remote account echo checking for .ssh directory on remote system ssh $user@$REM "if [ ! -d /home/$user/.ssh ]; then mkdir /home/$user/.ssh; fi"
# share the public key (using local hostname) echo copying the public key scp ~/.ssh/id_rsa.pub $user@$REM:/home/$user/$user-$LOC.pub
# put the public key into the proper location echo adding key to authorized_keys ssh $user@$REM "cat /home/$user/$user-$LOC.pub >> /home/$user/.ssh/authorized_ke ys"
# set permissions on authorized_keys and .ssh (might be OK already) echo setting permissions ssh $user@$REM "chmod 600 ~/.ssh/authorized_keys" ssh $user@$REM "chmod 700 ~/.ssh"
# try it out -- should NOT ask for a password echo testing -- if no password is requested, you are all set ssh $user@$REM /bin/hostname
脚本已经配置为在你每次必须输入密码时告诉你它正在做什么。交互看起来是这样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
$ ./rem_login_setup target system> fruitfly target user> lola checking for .ssh directory on remote system lola@fruitfly's password: copying the public key lola@fruitfly's password: id_rsa.pub 100% 567 219.1KB/s 00:00 adding key to authorized_keys lola@fruitfly's password: setting permissions lola@fruitfly's password: testing -- if no password is requested, you are all set fruitfly
在上面的场景之后,你就可以像这样登录到 lola 的帐户:
1 2
$ ssh lola@fruitfly [lola@fruitfly ~]$
一旦设置了免密登录,你就可以不需要键入密码从 boss 系统登录到 target 系统,并且运行任意的 ssh 命令。以这种免密的方式运行并不意味着你的帐户不安全。然而,根据 target 系统的性质,保护你在 boss 系统上的密码可能变得更加重要。