expect
expect,期待。这个工具大体上来说,可以模拟按键,解决在终端自动化的事。基本的模式,出现了什么字符串,然后,输入什么命令。类似于,一问一答的模式。
用途,管理多台机器时,自动化操作。比如,通过堡垒机,执行命令,再访问目标机器。expect,非常适合。
资源
安装
yum install expect -y
#先安装expect
注意
回车
send 后的字符串的换行符号不能少,\r。否则会莫名的卡在某处。
send "yxy7714707@\r"
两中运行模式,一种以expect来解析脚本运行,此时,如果想要进行交互,需要interact。
另外一种,使用sh,以这种模式调用expect <<EOL。
使用
1.测试用法
如果想停留在终端,省略下面的
exit.
#!/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
6.参数
#!/usr/bin/expect
# set Variables
set password [lrange $argv 0 0]
set ipaddr [lrange $argv 1 1]
set scriptname [lrange $argv 2 2]
set arg1 [lrange $argv 3 3]
set timeout -1
spawn ssh yourusername@$ipaddr $scriptname $arg1
match_max 100000
expect "*?assword:*"
# Send password aka $password
send -- "$password\r"
# send blank line (\r) to make sure we get back to gui
send -- "\r"
expect eof