使用ssh公钥实现免密码登录服务器

ssh 无密码登录要使用公钥与私钥。linux下可以用用ssh-keygen生成公钥/私钥对,CentOS为例。首先在客户端上创建一对公私钥

yum -y install openssh

systemctl start sshd

systemctl enable sshd

/etc/ssh/ssh_config       客户端配置文件

/etc/ssh/sshd_config     服务器配置文件

vim /etc/ssh/ssh_config

IdentityFile ~/.ssh/id_rsa(系统默认)

vim /etc/ssh/sshd_config(以下三条,只有第三条是默认开启的)

 RSAAuthentication yes # 启用 RSA 认证

 PubkeyAuthentication yes # 启用公钥私钥配对认证方式

 AuthorizedKeysFile .ssh/authorized_keys # 公钥文件路径

有机器A(192.168.1.155),B(192.168.1.181)。现想A通过ssh免密码登录到B。

首先以root账户登陆为例。

ssh-keygen -t rsa -P ''

-t参数就是指定要生成的密钥类型,你这里指定的是rsa

-P就是你提供的密码, '' 就表示空密码,也可以不用-P参数,这样就要三车回车,用-P就一次回车。

-f是密钥的生成后的保存文件位置,默认/root/.ssh/

系统默认采用的ssh的rsa密钥名称:(可以自己命名,如id_rsa_jrl   id_rsa_jrl.pub)

id_rsa      私钥

id_rsa.pub   公钥

下述命令产生不同类型的密钥

ssh-keygen -t dsa

ssh-keygen -t  rsa

ssh-keygen -t  rsa1

把A机下的/root/.ssh/id_rsa_jrl.pub 复制到B机的 /root/.ssh/authorized_keys文件里

ssh-copy-id -i  ~/.ssh/id_rsa.pub 用户名@对方机器IP (注意不要忘记了参数-i)

ssh-copy-id -i  id_rsa_jrl.pub   root@192.168.1.181

由于还没有免密码登录过,所以要输入一次B机的root密码。

4.A机登录B机。

[root@A ~]# ssh -p 35222 root 192.168.1.181

The authenticity of host '192.168.1.181 (192.168.1.181)' can't be established.

RSA key fingerprint is 00:a6:a8:87:eb:c7:40:10:39:cc:a0:eb:50:d9:6a:5b.

Are you sure you want to continue connecting (yes/no)? yes

Warning: Permanently added '192.168.1.181' (RSA) to the list of known hosts.

Last login: Thu Jul  3 09:53:18 2008 from root

[root@B ~]#

第一次登录是时要你输入yes。

现在A机可以无密码登录B机了


在脚本中调用ssh密码scp文件如下:sshpass


http://blog.csdn.net/nfer_zhuang/article/details/42646849

-p是直接指定密码,-f是从文件中读取密码

yum -y install sshpass

sshpass -p test  scp -P666  -r  root@ip:/root/www_online/war/*   /root/war


猜你喜欢

转载自blog.51cto.com/7072753/2135325