Linux Expect 用法
關(guān)鍵字解釋:
spawn????交互程序開(kāi)始后面跟命令或者指定程序
expect????獲取匹配信息匹配成功則執(zhí)行expect后面的程序動(dòng)作
send exp_send????用于發(fā)送指定的字符串信息
exp_continue????在expect中多次匹配就需要用到
send_user????用來(lái)打印輸出 相當(dāng)于shell中的echo
exit????退出expect腳本
eof????expect執(zhí)行結(jié)束 退出
set????定義變量
puts????輸出變量
set timeout????設(shè)置超時(shí)時(shí)間
案例:
1.編寫(xiě)copykey.sh腳本,自動(dòng)生成密鑰并分發(fā)key.
#!/bin/bash
# 判斷id_rsa密鑰文件是否存在
if [ ! -f ~/.ssh/id_rsa ];then
ssh-keygen -t rsa -P "" -f ~/.ssh/id_rsa
else
echo "id_rsa has created ..."
fi
#分發(fā)到各個(gè)節(jié)點(diǎn),這里分發(fā)到host文件中的主機(jī)中.
while read line
? do
? ? user=`echo $line | cut -d " " -f 2`
? ? ip=`echo $line | cut -d " " -f 1`
? ? passwd=`echo $line | cut -d " " -f 3`
? ? expect <<EOF
? ? ? set timeout 10
? ? ? spawn ssh-copy-id $user@$ip
? ? ? expect {
? ? ? ? "yes/no" { send "yes\n";exp_continue }
? ? ? ? "password" { send "$passwd\n" }
? ? ? }
? ? expect "password" { send "$passwd\n" }
EOF
? done <? hosts
2.shell調(diào)用expect執(zhí)行多行命令
#!/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 "]#" { send "useradd hehe\n" }
? ? expect "]#" { send "touch /tmp/test.txt\n" }
? ? expect "]#" { send "exit\n" } expect eof
EOF?
#./ssh5.sh 192.168.1.10 root 123456