expect+shell脚本实现免密登录


简介: 此脚本需要用到expect和openssh的知识点。
关于openssh可见往期文章 点此前往

1. expect

参数 解释
expect 自动应答命令(用于交互式命令的自动执行)
set timeout 1 等待1秒再向下执行/-1为永不超时
set NAME [ lindex $argv 0 ] 定义变量
sapwn 监控程序
send 发送问题答案给交互命令
\r 在终端敲回车
exp_continue 继续回答下面的
expect eof 表示回答完那些问题后,退出expect环境
interact 问题回答完后留在交互界面
//下载expect
[root@localhost ~]# yum -y install expect
[root@localhost ~]# expect -div
expect version 5.45
expect version 5.45
[root@localhost ~]# yum -y install expect
[root@localhost ~]# which expect
/usr/bin/expect

2. 脚本编辑

写脚本首先要手动执行一遍了解过程

//这是第一种情况
[root@localhost ~]# ssh-keygen 
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:lqC2uv6o3F6X2umq2bzf57MpC40Rj0HB49gSfTH3uf0 root@localhost.localdomain
The key's randomart image is:
+---[RSA 2048]----+
|      oo.o..     |
|     ..+ .o . .  |
|      *oo    o   |
|     + +=.    o  |
|    o .oS.   . . |
|   . . .=       .|
|    .. = .      E|
|. .o= + +. o.    |
|.+*Bo*== o=+o    |
+----[SHA256]-----+
总结一下就是ssh-keygen后按3下回车
//第二种情况,已经配置过免密,那么就要更新密码
[root@localhost ~]# ssh-keygen 
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
/root/.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 /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:jnrscl5RGkiz9qL6bKtKV/mxbVY/CVs8m/LsBEYexEE root@localhost.localdomain
The key's randomart image is:
[root@localhost ~]# vim ssh.sh 
[root@localhost ~]# cat ssh.sh 
#!/bin/bash

read -p "Which IP address you want to connect to?:" ip
read -s -p "and password:" pwd     #-s要在前面表示静默输出,保护密码

yum -y install openssh expect

expect << EOF     #表示里面的内容均由expect命令去执行

set timeout 30     #设置超时时间为30秒,下面的代码需在30秒钟内完成,如果超过,则退出。用来防止ssh远程主机网络不可达时卡住及在远程主机执行命令宕住

spawn   ssh-keygen  #激活一个交互式会话,在系统中创建一个进程

expect     {
    
    
        ".ssh/id_rsa)"       {
    
     send    "\r";  exp_continue } #捕捉关键字,然后回车
        "Overwrite (y/n)?"   {
    
     send    "y\r"; exp_continue } #捕捉关键字后输入y然后回车
        "no passphrase):"    {
    
     send    "\r";  exp_continue }
        "again:"             {
    
     send    "\r";  exp_continue }
}

spawn ssh-copy-id root@$ip

expect {
    
    
     "yes/no"   {
    
     send "yes\r";  exp_continue }
     "password" {
    
     send "$pwd\r"; exp_continue }
}
EOF

[root@localhost ~]# ./ssh.sh 
Which IP address you want to connect to?:192.168.216.200
and password:1
spawn ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
/root/.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 /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:xaplvcpVheYg5sR/JU6QBlg+jMy9hYqxR1k7AiqK9Bk root@localhost.localdomain
The key's randomart image is:
+---[RSA 2048]----+
|    .  o+...     |
|   . +.O +o. .   |
|...E. B &.= = o  |
|+.. o= * @ * +   |
|o  oo o S o =    |
|     . +   +     |
|      .   o      |
|       . o       |
|        o        |
+----[SHA256]-----+
spawn ssh-copy-id root@192.168.216.200
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.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.216.200'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.

2.1 测试

//恢复快照再次尝试
[root@localhost ~]# ./ssh.sh 
Which IP address you want to connect to?:192.168.216.200^H^H^H^H^C
[root@localhost ~]# ./ssh.sh 
Which IP address you want to connect to?:192.136^H^H^C
[root@localhost ~]# ./ssh.sh 
Which IP address you want to connect to?:192.168.216.179
and password:1
Failed to set locale, defaulting to C.UTF-8
CentOS Linux 8 - AppStream                                                                                                   441 kB/s | 9.3 MB     00:21    
CentOS Linux 8 - BaseOS                                                                                                      892 kB/s | 7.5 MB     00:08    
CentOS Linux 8 - Extras                                                                                                       14 kB/s |  10 kB     00:00    
Package openssh-8.0p1-5.el8.x86_64 is already installed.
Dependencies resolved.
=============================================================================================================================================================
 Package                                   Architecture                     Version                                   Repository                        Size
=============================================================================================================================================================
Installing:
 expect                                    x86_64                           5.45.4-5.el8                              baseos                           267 k
Upgrading:
 openssh                                   x86_64                           8.0p1-6.el8_4.2                           baseos                           521 k
 openssh-clients                           x86_64                           8.0p1-6.el8_4.2                           baseos                           667 k
 openssh-server                            x86_64                           8.0p1-6.el8_4.2                           baseos                           484 k
Installing dependencies:
 tcl                                       x86_64                           1:8.6.8-2.el8                             baseos                           1.1 M

Transaction Summary
=============================================================================================================================================================
Install  2 Packages
Upgrade  3 Packages

Total download size: 3.0 M
Downloading Packages:
(1/5): expect-5.45.4-5.el8.x86_64.rpm                                                                                        680 kB/s | 267 kB     00:00    
(2/5): openssh-8.0p1-6.el8_4.2.x86_64.rpm                                                                                    862 kB/s | 521 kB     00:00    
(3/5): openssh-server-8.0p1-6.el8_4.2.x86_64.rpm                                                                             726 kB/s | 484 kB     00:00    
(4/5): openssh-clients-8.0p1-6.el8_4.2.x86_64.rpm                                                                            725 kB/s | 667 kB     00:00    
(5/5): tcl-8.6.8-2.el8.x86_64.rpm                                                                                            852 kB/s | 1.1 MB     00:01    
-------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                        1.6 MB/s | 3.0 MB     00:01     
warning: /var/cache/dnf/baseos-929b586ef1f72f69/packages/expect-5.45.4-5.el8.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID 8483c65d: NOKEY
CentOS Linux 8 - BaseOS                                                                                                      153 kB/s | 1.6 kB     00:00    
Importing GPG key 0x8483C65D:
 Userid     : "CentOS (CentOS Official Signing Key) <[email protected]>"
 Fingerprint: 99DB 70FA E1D7 CE22 7FB6 4882 05B5 55B3 8483 C65D
 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial
Key imported successfully
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                                                                                                     1/1 
  Running scriptlet: openssh-8.0p1-6.el8_4.2.x86_64                                                                                                      1/1 
  Running scriptlet: openssh-8.0p1-6.el8_4.2.x86_64                                                                                                      1/8 
  Upgrading        : openssh-8.0p1-6.el8_4.2.x86_64                                                                                                      1/8 
  Installing       : tcl-1:8.6.8-2.el8.x86_64                                                                                                            2/8 
  Running scriptlet: tcl-1:8.6.8-2.el8.x86_64                                                                                                            2/8 
  Installing       : expect-5.45.4-5.el8.x86_64                                                                                                          3/8 
  Upgrading        : openssh-clients-8.0p1-6.el8_4.2.x86_64                                                                                              4/8 
  Running scriptlet: openssh-server-8.0p1-6.el8_4.2.x86_64                                                                                               5/8 
  Upgrading        : openssh-server-8.0p1-6.el8_4.2.x86_64                                                                                               5/8 
  Running scriptlet: openssh-server-8.0p1-6.el8_4.2.x86_64                                                                                               5/8 
  Running scriptlet: openssh-server-8.0p1-5.el8.x86_64                                                                                                   6/8 
  Cleanup          : openssh-server-8.0p1-5.el8.x86_64                                                                                                   6/8 
  Running scriptlet: openssh-server-8.0p1-5.el8.x86_64                                                                                                   6/8 
  Cleanup          : openssh-clients-8.0p1-5.el8.x86_64                                                                                                  7/8 
  Cleanup          : openssh-8.0p1-5.el8.x86_64                                                                                                          8/8 
  Running scriptlet: openssh-8.0p1-5.el8.x86_64                                                                                                          8/8 
  Verifying        : expect-5.45.4-5.el8.x86_64                                                                                                          1/8 
  Verifying        : tcl-1:8.6.8-2.el8.x86_64                                                                                                            2/8 
  Verifying        : openssh-8.0p1-6.el8_4.2.x86_64                                                                                                      3/8 
  Verifying        : openssh-8.0p1-5.el8.x86_64                                                                                                          4/8 
  Verifying        : openssh-clients-8.0p1-6.el8_4.2.x86_64                                                                                              5/8 
  Verifying        : openssh-clients-8.0p1-5.el8.x86_64                                                                                                  6/8 
  Verifying        : openssh-server-8.0p1-6.el8_4.2.x86_64                                                                                               7/8 
  Verifying        : openssh-server-8.0p1-5.el8.x86_64                                                                                                   8/8 

Upgraded:
  openssh-8.0p1-6.el8_4.2.x86_64                 openssh-clients-8.0p1-6.el8_4.2.x86_64                 openssh-server-8.0p1-6.el8_4.2.x86_64                
Installed:
  expect-5.45.4-5.el8.x86_64                                                     tcl-1:8.6.8-2.el8.x86_64                                                    

Complete!
spawn ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:qgc6dnL7BFeNCzbMC3MJ2/mWUfJ74J7rIN4t4sXxC8Y root@localhost.localdomain
The key's randomart image is:
+---[RSA 3072]----+
|    .   . .      |
|     * o *       |
|    + @ + +      |
|     = * = o     |
|    . o S o .    |
|    .o = + o     |
|   . .+ E +      |
|  = o+o=.+ o     |
| . =o=+..o=      |
+----[SHA256]-----+
spawn ssh-copy-id root@192.168.216.179
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.216.179 (192.168.216.179)' can't be established.
ECDSA key fingerprint is SHA256:gkMCzwLaISQUrSVhbQrfQfP3iKhVouSKK8Y8y0mr3SY.
Are you sure you want to continue connecting (yes/no/[fingerprint])? 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
root@192.168.216.179'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.

[root@localhost ~]# ssh 192.168.216.179
Last login: Sat Oct 23 09:15:42 2021 from 192.168.216.1
满足正常使用

猜你喜欢

转载自blog.csdn.net/weixin_46115601/article/details/120926319