使用expect实现shell自动交互

安装expect

sudo apt install expect

要执行的脚本

#!/bin/bash
# cpao.sh

ssh-keygen -f "/home/lyq/.ssh/known_hosts" -R "192.168.1.10"
scp sd.sh ao_app.elf brdc* root@192.168.1.10:/root
ssh root@192.168.1.10

交互输入脚本

#!/usr/bin/expect
# ca.tcl

set timeout 86400;
spawn ./cpao.sh
expect {
        "yes/no*" {
                send "yes\n";
                exp_continue
        }
        "password*" {
                send "analog\n";
                exp_continue
        }
        "#*" {
                send "./sd.sh\nls -l\n"
        }
}

# 执行完成后保持交互状态,把控制权交给控制台,这个时候就可以手工操作了。
# 如果没有这一句登录完成后会退出,而不是留在远程终端上。
interact          

最后实际执行ca.tcl脚本

lyq@lyq-vivado2019:~$ ./ca.tcl 
spawn ./cpao.sh
Host 192.168.1.10 not found in /home/lyq/.ssh/known_hosts
The authenticity of host '192.168.1.10 (192.168.1.10)' can't be established.
ECDSA key fingerprint is SHA256:WEacrNZg/G744tSugjYReaTJrVd+BhPt0AWcF7ANetU.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.1.10' (ECDSA) to the list of known hosts.
root@192.168.1.10's password: 
sd.sh                                                                                                                                                                    100%  118   158.1KB/s   00:00    
ao_app.elf                                                                                                                                                               100% 1779KB   4.6MB/s   00:00     
root@192.168.1.10's password: 
Welcome to:
# ./sd.sh
# ls -l
total 2048
-rwx------    1 root     root       1821744 Jan  1 00:15 ao_app.elf
-rwx------    1 root     root           118 Jan  1 00:15 sd.sh
# 

可见,上面自动完成了yes确认和scp和ssh的密码输入,并且登录后成功执行了远程命令。

posted @ 2023-08-02 17:29  清哥他弟  阅读(4)  评论(0编辑  收藏  举报