shell ssh自动登录远程主机配置实例

发布时间:2020-09-03编辑:脚本学堂
shell脚本中实现ssh自动登录远程主机的方法,ssh通过密钥对自动登录的配置实例,不了解的同学参考下。

首先,生成新的ssh密钥对。(linux免密钥SSH登陆配置教程详解ssh密钥对的配置方法
 

复制代码 代码示例:
[guo@guo zuo]$ ssh-keygen -f id_ras -t rsa
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in id_ras.
Your public key has been saved in id_ras.pub.
The key fingerprint is:
17:ca:c3:37:8f:60:86:42:d0:0d:b7:4d:70:a1:b2:a3 guo@guo
The key's randomart image is:
+--[ RSA 2048]----+
|  ...oo.+.       |
|   ....*         |
|    o o . .      |
|   . o + . .     |
|    + . S +      |
|   . o o = +     |
|  E       . .    |
|                 |
|                 |
+-----------------+
 

当程序询问密码时按【enter】键,表示不设密码,此时会在工作目录中产生私钥,密码文件名为is_rsa,以及公钥文件id_psa.pub。
 

[guo@guo zuo]$ ls id*
id_ras  id_ras.pub

把一个公钥复制到远程主机:
 

[guo@guo zuo]$ ssh-copy-id root@222.24.21.61
root@222.24.21.61's password:
Now try logging into the machine, with "ssh 'root@222.24.21.61'", and check in:

  .ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.
 

这一次需要输入密码。

配置完成,以后就不用再输入密码了。

执行脚本
 

[guo@guo zuo]$ cat guossh.sh
#!/bin/sh
ssh root@222.24.21.61
[guo@guo zuo]$ sh guossh.sh
Last login: Sun Nov 13 20:28:30 2011 from 222.24.21.61
 

使用以上shell/ target=_blank class=infotextkey>shell脚本成功登录ssh远程主机。