【就业班作业】【第九周】使用expect实现自动登录系统。
第一步:编写自动登录脚本
#!/bin/bash # if [ $# != 2 ];then echo "Usage:./command username ipaddress-------eg:./sshautologin.sh root 192.168.0.17" exit else rpm -q expect &> /dev/null || yum -y install expect &> /dev/null PASS=xxxxx expect <<EOF spawn ssh $1@$2 expect { "yes/no" { send "yes\n";exp_continue } "password:" { send "$PASS\n" } } expect of EOF fi
另一种:
#!/usr/bin/expect # set timeout 3 set PASS "xxxx" spawn ssh root@192.168.0.17 expect { "yes/no" { send "yes\n";exp_continue } "password:" { send "$PASS\n";exp_continue } } interact
第二步:脚本执行测试
[root@localhost data]# ./sshautologin.sh root 192.168.0.17 Usage:./command username ipaddress,eg:./sshautologin.sh root 192.168.0.17 spawn ssh root@192.168.0.17 root@192.168.0.17's password: Last login: Fri Sep 18 17:03:41 2020 from 192.168.0.14 [root@lab-CentOS-6 ~]# [root@lab-CentOS-6 ~]# [root@localhost data]# [root@localhost data]#
expect常用参数
spawn 交互程序开始后面跟命令或者指定程序
expect 获取匹配信息匹配成功则执行expect后面的程序动作
send exp_send 用于发送指定的字符串信息
exp_continue 在expect中多次匹配就需要用到
send_user 用来打印输出 相当于shell中的echo
exit 退出expect脚本
eof expect执行结束 退出
set 定义变量
puts 输出变量
set timeout 设置超时时
(结束)