centos7 自動互動expect 安裝使用
1.安裝
https://www.cnblogs.com/rocky-AGE-24/p/7256800.html
安裝expect命令 兩種方式
yum安裝
yum -y install expect
手動安裝
expect以及tcl版本
複製程式碼
#!/bin/bash
oldpath=`pwd`
tar -zxf tcl8.4.20-src.tar.gz
#3.安裝配置
cd tcl8.4.20/unix
./configure --prefix=/usr/tcl --enable-shared
make
make install
#注意:
#1、安裝完畢以後,進入tcl原始碼的根目錄,把子目錄unix下面的tclUnixPort.h copy到子錄generic中。
cp ./tclUnixPort.h ../generic/
#(二)expect 安裝 (需Tcl的庫)
#2.解壓縮原始碼包
cd $oldpath
tar xzf expect5.45.tar.gz
#3.安裝配置
cd expect5.45
./configure --prefix=/usr/expect --with-tcl=/usr/tcl/lib --with-tclinclude=../tcl8.4.20/generic
make
make install
ln -s /usr/tcl/bin/expect /usr/expect/bin/expect
ln -s /usr/tcl/bin/expect /usr/bin/expect
複製程式碼
testcase
複製程式碼
#!/bin/bash
#create hadoop user
user1=$1
useradd $user1
expect -c "
set timeout -1;
spawn passwd $user1;
expect {
*password:* {send -- hadoop\r;exp_continue;}
eof {exit 0;}
}"
# 更改使用者組為root
usermod -g root $user1
#test comand
# id $user1
2.使用
以拉取遠端伺服器mysql備份為例 總共2個檔案,備份檔案自己建立
vimysqlbackup.sh
#!/bin/sh
source /etc/profile
DATE=`date +%Y%m%d`
mysqlfile=********專案名_${DATE}*.sql.gz
password=********
#傳遞密碼和檔名到mysql檔案
./mysql $password $mysqlfile
echo "pull mysqlfile end"
vimysql
#!/usr/bin/expect
set password [lindex $argv 0]
set mysqlfile [lindex $argv 1]
#全部拉取
#spawn scp -r root@ip:/data/mysqlbackup/${BACK_DATA}.sql.gz /home/backup/mysqlbackup
#拉取指定的檔案
spawn scp -r root@ip:/data/mysqlbackup/$mysqlfile /home/backup/mysqlbackup
expect {
"密碼:"
{
send "$password\n"
}
"password"
{
send "$password\n"
}
"yes/no"
{
sleep 5
send_user "send yes"
send "yes\n"
}
eof
{
sleep 5
send_user "eof\n"
}
}
set timeout 3000
send "exit\r"
expect eof