expect的两种用法

yum install expect -y
#先安装expect

1.测试用法
#!/usr/bin/expect
#解释语言,这边运行要以./运行,bash运行会报错
spawn ssh root@192.168.0.14
#启动新的进程
expect "*password:"
#进程接收字符串,匹配
send "yxy7714707@\r"
#前面匹配到了就输入 “ ” 里的内容
expect "*#"
send "ifconfig>>123.txt\r"
send "exit\r"
interact

2.在sh脚本里调用
#!/bin/bash
ip=$1
#传递参数
user=$2
password=$3
expect <<EOF
set timeout 10
spawn ssh $user@$ip
expect {
"yes/no" { send "yes\n";exp_continue }
"password" { send "$password\n" }
}
#一个交互用一个expect{} 括起来,这个交互就是登陆的
expect "]#" { send "date>>123.txt\n" }
expect "]#" { send "exit\n" }
#退出
expect eof
EOF

3.实战程序(传递公钥文件实现无密码登录)
#!/bin/bash
x=`cat .ssh/id_rsa.pub`
ip=$1
password=$2
if [ ! -f "/root/.ssh/id_rsa.pub" ];then
echo "文件不存在"
expect <<EOF
set timeout -1
spawn ssh-keygen -t rsa
expect {
"Enter file in which to save the key (/root/.ssh/id_rsa):" { send "\r"; exp_continue}
#简写 "*(/root/.ssh/id_rsa):" { send "\r"; exp_continue}
"Enter passphrase (empty for no passphrase):" { send "\r"; exp_continue}
"Enter same passphrase again:" { send "\r"; exp_continue}
}
#生成私钥 公钥文件(.ssh里的 id_rsa id_rsa.pub的两个文件)
expect eof
EOF
fi


expect <<EOF
set timeout 10
spawn ssh-copy-id $ip
expect {
"connecting (yes/no)?" { send "yes\n";exp_continue }
#保存对方的密码指纹
"password:" { send "$password\n" }
#输入密码
}

expect eof
EOF

4.实战程序2
#!/bin/bash
expect <<EOF
set timeout 10
spawn bash /root/***.sh #打开某个脚本
expect "请输入数字" { send "14\n" }
expect "默认:" { send "6\n" }
expect eof
EOF

PS :注意匹配为模糊匹配,可以不用写全,写个关键字即可
实战脚本

yum install expect -y
fsip=192.168.0.25
password=yxy7714707@
expect <<EOF
set timeout 10
spawn scp /etc/hosts $fsip:/etc/hosts
expect {
"connecting (yes/no)?" { send "yes\n";exp_continue }
#保存对方的密码指纹
"password:" { send "$password\n" }
#输入密码
}

expect eof
EOF

#脚本用途,传送本地的hosts文件给 对方

#5实战

登录后复制
set timeout 10
expect <<EOF
spawn ssh admin@100.1.1.1
expect {
"Password:" { send "$password\n"; exp_continue }
#exp_continue 多次匹配的意思
"<USG6100>" { send "system-view\r" ; exp_continue }
"]" { send "undo nat server name 0\n"; }
}
expect {
"]" { send "nat server protocol tcp global $ip 2333 inside 192.168.0.26 2333\n"; }
#有BUG就在起一行expect
}

expect eof
EOF
-----------------------------------

转载:expect 两种用法
https://blog.51cto.com/u_13620944/2440856

posted on 2022-03-24 14:20  大兄弟666  阅读(424)  评论(0编辑  收藏  举报