1.expect.sh
expect的核心spawn expect send set
spawn 调用要执行的命令
expect 等待命令提示信息的出现,也就是捕捉用户输入的提示
send 发送需要交互的值,代替了用户手动输入的内容
set 设置变量值
set timeout 300 300秒超时 如果300秒没有expect内容出现就退出
设置expect永不超时
set timeout -1
interact 执行完成后保持交互状态。如果没有这一句登陆完成后会退出
expect eof 这个一定要加,与spawn对应表示捕获终端输出信息终止,类似于if ...then ...fi
expect脚本必须以interact或expect eof结束,执行自动化任务通常expect eof就够了。
例:
TESTHOST=(
10.146.3.134
)
for ip in ${TESTHOST[@]};do
/usr/bin/expect << EOF
set timeout 10
spawn scp -p /root/sys_secrity.sh root@$ip:/root/
expect {
"(yes/no)" {send "yes\n"; exp_continue}
"password:" {send "passwd.....\n"}
}
expect eof
EOF
done
for ip in ${TESTHOST[@]};do
/usr/bin/expect << EOF
set timeout 10
spawn ssh root@$ip sh /root/sys_secrity.sh
expect {
"password:" {send "passwd.....\n"}
}
expect eof
EOF
done
1.远程登录到Server上;
2.将Server上的文件拉到当前主机;
TRANSFER_HOST=10.146.3.134
TRANSFER_SSH_PORT=2233
TRANSFER_USER=my_admin
TRANSFER_PASSWORD=mypassword
TRANSFER_PROJECT=/home/my_admin/deploy/transfer/*
DEPLOY_DIR=$(cd -P -- "$(dirname -- "$0")" && pwd -P)
fuction remote_transfer(){
echo "$1"
shift 1
expect << EOF
set timeout 30
spawn $@
expect {
"(yes/no)" {send "yes\r"; exp_continue}
"password:" {send "`echo $TRANSFER_PASSWORD |base64 -d`\r"}
}
expect eof
EOF
}
remote_transfer "Download files from remote JumpServer now ......" "scp -P ${TRANSFER_SSH_PORT} ${TRANSFER_USER}@${TRANSFER_HOST}:${TRANSFER_PROJECT} ${DEPLOY_DIR}"
例:密钥批量分发
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

浙公网安备 33010602011771号