expect腳本簡單應用----2

用expect腳本執行命令

#!/usr/bin/expect
#set user [lindex $argv 0]
set user root
set host 192.168.1.120
#set host [lindex $argv 1]
set passwd "8023jun12"
spawn ssh $user@$host
expect "password:"
send "$passwd\r"
#interact
expect "]*"
send "w\r"
interact
#expect "]*"
#send "exit\r"

執行過程:

[root@slave expect]# ./expect.exp 
spawn ssh [email protected]
[email protected]'s password: 
Last login: Tue Dec 27 09:39:52 2016 from slave
[root@master ~]# w
 09:41:30 up  3:01,  2 users,  load average: 0.00, 0.00, 0.00
USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
root     pts/0    192.168.1.107    06:41    2:19   0.03s  0.03s -bash
root     pts/1    slave            09:41    0.00s  0.00s  0.00s w
[root@master ~]#

###########################################################################################

用expect腳本搭建一個創建文件系統:

有三個文件:

expect.exp文件用來存放expect腳本:

user:腳本用來存放用戶和對應的ip地址

touch.sh: 用來實際執行:

腳本具體代碼如下:

cat expect.exp
#!/usr/bin/expect
set user [lindex $argv 0]
set host [lindex $argv 1]
set passwd "8023jun12"
set timeout 60
spawn ssh $user@$host
expect "password:"
send "$passwd\r"
expect "]*"  
send "touch 12\r"
expect "]*"
send "exit\r"
cat user
root:192.168.1.120
root:192.168.1.121
cat touch.sh
#!/bin/bash
#在服務器中創建一個文件12
 [ -x expect.exp ] || chmod +x expect.exp
for i in `cat user`; do
    username=`echo $i |awk -F":" '{print $1}'` 
    hostip=`echo $i |awk -F":" '{print $2}'` 
    ./expect.exp $username $hostip
done

運行的時候直接執行touch.sh腳本即可,不過三個腳本要放在同一目錄下面:

sh touch.sh


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章