使用SSH密钥方式登录ubuntu Linux,指令(ssh-keygen 和 ssh-copy-id)
实验目的
从myVM1(本地主机)上登录myVM2(远程主机)。采用密钥方式,不输入密码。
测试环境
主机:window7 sp1 64位 专业版
虚拟机:VMware workstation 12 player
虚拟机操作系统: ubuntu 16.4
请确保你的ubuntu虚拟机能够连接Internet。VMware建议使用NAT方式联网。
- myVM1(本地主机) 用户 lion IP:192.168.145.128
- myVM2(远程主机) 用户 novak IP:192.168.145.129
如何修改linux计算机名参考如下链接见
http://www.cnblogs.com/lion-zheng/p/7528774.html
在vm2上的操作
目标是从VM1上远程登陆到VM2上。因此,VM2需要运行SSH服务器。
步骤1 检查ssh-server有没有启动
ps -e | grep ssh
如果只有ssh-agent,而没有sshd,说明ssh-server没有启动
#### 步骤2 安装OpenSSH服务器 安装前可以通过linux内的浏览器是否能够打开网页来验证能否上网。虚拟机VMware的网络可以设置为NAT模式。
sudo apt-get install openssh-server
再次检查ssh-server是否启动,看到sshd说明服务已经启动
ps -e | grep ssh
##在vm1上的操作
步骤0 尝试密码登录 (option)
即使没有建立密钥,也应该可以从vm1上通过用户名+密码的方式登录到vm2
可以使用
ssh novak@192.168.145.129
或
ssh 192.168.145.129
来尝试登陆。能够登录证明两个虚拟机(计算机)之间的连接正常,并且远程主机(myvm2)的SSH服务运行正常。
步骤1 使用ssh-keygen指令建立密钥
ssh-keygen -t rsa
以下是执行指令的截屏,在/home/lion/.ssh/ 目录下生成id_rsa和id_rsa.pub两个文件。注意.ssh是一个隐藏文件夹,在目录中CTRL+H可以显示隐藏文件。
lion@myvm1:~$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/lion/.ssh/id_rsa):
Created directory '/home/lion/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/lion/.ssh/id_rsa.
Your public key has been saved in /home/lion/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:I80d9ilw5GZyNZq2KAZfQHh70o97KonVDQ1hZs7+SbE lion@myvm1
The key's randomart image is:
+---[RSA 2048]----+
| oo =.. o |
| . .B.o + . |
| .. o*o& |
| oo=+%.* . |
| =+S=E o |
| ..oo+oo |
| o . .o |
| . o . . |
| ..o |
+----[SHA256]-----+
lion@myvm1:~$
#### 步骤2 执行ssh-copy-id 该指令将vm1生成的密钥,写入到vm2的 /home/novak/.ssh/authorized_keys 文件中。 (novak是我的用户名,你的可能会不同)
ssh-copy-id -i ~/.ssh/id_rsa.pub novak@192.168.145.129
novak是我的myvm2的用户名,192.168.145.129是我的myvm2的地址,相应的替换为你的用户名和地址。
"-i ~/.ssh/id_rsa.pub" 是表示home文件夹下的路径。也可以使用完整路径:
ssh-copy-id -i /home/lion/.ssh/id_rsa.pub novak@192.168.145.129
指令执行截图
lion@myvm1:~$ ssh-copy-id -i ~/.ssh/id_rsa.pub novak@192.168.145.129
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/lion/.ssh/id_rsa.pub"
The authenticity of host '192.168.145.129 (192.168.145.129)' can't be established.
ECDSA key fingerprint is SHA256:rOFueqsS2qpZZr0KoPO9sbezts+CIcwrVtmsX1WoLEw.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
novak@192.168.145.129's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'novak@192.168.145.129'"
and check to make sure that only the key(s) you wanted were added.
步骤3 从myvm1(本地主机)登录到myvm2(远程主机)
ssh novak@192.168.145.129
登录过程已经不需要输入密码了。请注意,这个密钥只对novak这个账户生效。
posted on 2017-09-15 23:47 lion_zheng 阅读(1516) 评论(0) 编辑 收藏 举报