expect是一個自動化交互套件,主要應用於執行命令和程序時,系統以交互形式要求輸入指定字符串,實現交互通信。
expect自動交互流程:
spawn啓動指定進程---expect獲取指定關鍵字---send向指定程序發送指定字符---執行完成退出.
expect常用命令總結:
spawn 交互程序開始後面跟命令或者指定程序
expect 獲取匹配信息匹配成功則執行expect後面的程序動作
send exp_send 用於發送指定的字符串信息
exp_continue 在expect中多次匹配就需要用到
send_user 用來打印輸出 相當於shell中的echo
exit 退出expect腳本
eof expect執行結束 退出
set 定義變量
puts 輸出變量
set timeout 設置超時時間
示例:
1.ssh登錄遠程主機執行命令,執行方法 expect 1.sh 或者 ./1.sh
# vim 1.sh
#!/usr/bin/expect
spawn ssh [email protected] df -Th
expect "*password"
send "123456\n"
expect eof
2. ssh遠程登錄主機執行命令,在shell腳本中執行expect命令,執行方法sh 2.sh、bash 2.sh 或./2.sh都可以執行.
#!/bin/bash
passwd='123456'
/usr/bin/expect <<-EOF
set time 30
spawn ssh [email protected] df -Th
expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$passwd\r" }
}
expect eof
EOF
3.expect執行多條命令
#!/usr/bin/expect -f
set timeout 10
spawn sudo su - root
expect "*password*"
send "123456\r"
expect "#*"
send "ls\r"
expect "#*"
send "df -Th\r"
send "exit\r"
expect eof
4. 創建ssh key,將id_rsa和id_rsa.pub文件分發到各臺主機上面。
1.創建主機配置文件
[root@localhost script]# cat host
192.168.1.10 root 123456
192.168.1.20 root 123456
192.168.1.30 root 123456
[root@localhost script]# ls
copykey.sh hosts
2.編寫copykey.sh腳本,自動生成密鑰並分發key.
[root@localhost script]# vim copykey.sh
#!/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
#分發到各個節點,這裏分發到host文件中的主機中.
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
5. shell調用expect執行多行命令.
#!/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