SSH 免密码登陆
方法使用的是ssh的公钥加密私钥解密方式实现免密码登陆。简单几步就能完成:
- 在本机产生ssh密钥对
- 将本机的公钥上传到目标机
- 登陆
1.本机生成ssh密钥
命令ssh-keygen
ubuntu@ubuntu:~$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/ubuntu/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/ubuntu/.ssh/id_rsa.
Your public key has been saved in /home/ubuntu/.ssh/id_rsa.pub.
The key fingerprint is:
a0:b7:cd:86:e5:43:27:93:9d:xx:xx:xx:xx:xx:xx:xx ubuntu@ubuntu
The key's randomart image is:
+---[RSA 2048]----+
| |
| . |
| . + |
| ...Eo.. |
| . .=S.+ |
| . O.+ . |
| o *o. |
| ..... . |
| .o |
+-----------------+
id_ras.pub
为公钥,一般放在~/.ssh/
下面,将其上传到目标机,这样使用本机的私密id_ras
解开目标机器的公钥
2.上传公钥
命令ssh-copy-id
ubuntu@ubuntu:~$ ssh-copy-id -i .ssh/id_rsa.pub [email protected]
/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
[email protected]'s password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh '[email protected]'"
and check to make sure that only the key(s) you wanted were added.
如此就将 id_rsa.pub
上传到目标机192.168.1.1
的root
用户下的.ssh
文件夹下,文件名为authorized_keys
对于一般的linux系统就可以完成免密码登陆了。但是openwrt的服务为dropbear,dropbear是一个轻量级ssh服务,所以要将公钥拷贝到此文件夹下。
root@OpenWrt:~# cp .ssh/authorized_keys /etc/dropbear/
注意authorized_keys
的权限至少为600
3.登陆
使用如下指令就免密码登陆了
ubuntu@ubuntu:~$ ssh [email protected]
BusyBox v1.23.2 (2015-11-09 13:52:23 CST) built-in shell (ash)
_______ ________ __
| |.-----.-----.-----.| | | |.----.| |_
| - || _ | -__| || | | || _|| _|
|_______|| __|_____|__|__||________||__| |____|
|__| W I R E L E S S F R E E D O M
-----------------------------------------------------
CHAOS CALMER (Chaos Calmer, r47390)
-----------------------------------------------------
* 1 1/2 oz Gin Shake with a glassful
* 1/4 oz Triple Sec of broken ice and pour
* 3/4 oz Lime Juice unstrained into a goblet.
* 1 1/2 oz Orange Juice
* 1 tsp. Grenadine Syrup
-----------------------------------------------------
这是一个主机对应一个目标机,当多个主机登陆时该如何操作,方法类似
- 新的主机如上操作,生成密钥对,目标机添加公钥,如下
root@OpenWrt:/# cat /root/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDYM923Z1gt9xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDsZgYC5zSvpxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- 另一种方法是,将主机的私钥分享给其他机器,使用如下命令登陆
ssh -i id_rsa [email protected]
注意is_rsa
的权限是600,但是这种方式不安全,因为私钥共享了
那么当私钥真的被滥用了,该怎么办。方法如下:
删除目标机的公钥
删除本地密钥对,重新生成。或者使用
ssh-keygen -p
重新生成即可
免密码登陆在远程操作,定时操作等非常实用,此外scp也可以通过这样的方式免密码传文件
scp -i id_rsa xxxx [email protected]
参考文献
Getting started with SSH - Directory and file permissions
3 Steps to Perform SSH Login Without Password Using ssh-keygen & ssh-copy-id
公开密钥加密