有时候经常登录某台主机,会懒得输入密码,输入个用户名登录,像我这种更懒的,密码也懒得输入:
使用openssh实现免密码登录(仅输入用户名就可以了)
原理:使用公钥认证(私钥加密公钥解密可以进行身份验证)
客户端生成一对密钥(public key和private key),通过将生成的公钥保存到需要认证的服务器的~/.ssh/authriedkey文件中,并且将.ssh目录的权限设置为644、authrizedkey权限设置为600即可
---
ssh密钥生成
HuaiqingdeMBP:vagrant huaiqingcheng$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/huaiqingcheng/.ssh/id_rsa):
/Users/huaiqingcheng/.ssh/id_rsa already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /Users/huaiqingcheng/.ssh/id_rsa.
Your public key has been saved in /Users/huaiqingcheng/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:CCRo8ATutB5d8kXw2ApP0i2EB3yoPzWkPOnkjXHX4fw huaiqingcheng@HuaiqingdeMBP.lan
The key's randomart image is:
+---[RSA 2048]----+
|+o+.=o.. |
|o+ *o+* . |
|.o++B* =+ . |
|o.oBO=+o + |
| +=.B++ S . |
|. .* . E |
| . . |
| |
| |
+----[SHA256]-----+
ssh-copy-id 复制公钥(需要输入一次用户密码)
HuaiqingdeMBP:vagrant huaiqingcheng$ ssh-copy-id root@192.168.0.113
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/huaiqingcheng/.ssh/id_rsa.pub"
/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
root@192.168.0.113's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.0.113'"
and check to make sure that only the key(s) you wanted were added.
测试完成,免密码,需要输入用户名:
HuaiqingdeMBP:vagrant huaiqingcheng$ ssh root@192.168.0.113
Last login: Mon Mar 27 14:30:10 2017
Welcome to your Vagrant-built virtual machine.
[root@bogon ~]#
或者手动复制公钥/Users/huaiqingcheng/.ssh/id_rsa.pub到目标虚机/root/.ssh/authorized_keys文件中,~/.ssh目录的权限700,authorized_key的权限为600
用openssh实现免用户名+密码登录
在~/.ssh/目录下建立config文件,编辑内容,绑定用户名和公钥
Host 192.168.0.113 #
HostName 192.168.0.113 #FQDN或者IP
User root
Port 22
IdentityFile ~/.ssh/id_rsa #公钥位置
测试
HuaiqingdeMBP:vagrant huaiqingcheng$ ssh 192.168.0.113
Last login: Mon Mar 27 14:33:19 2017 from 192.168.0.101
Welcome to your Vagrant-built virtual machine.
[root@bogon ~]#