2013-07-15 25 views
5

我所試圖做的是:讀取的文件轉換成String,做一個循環,expect腳本

  1. 創建.exp文件,該文件會從*.txt文件從同一目錄中讀取並分析所有的內容在文本文件中放入期望腳本中的字符串變量。
  2. 循環包含一系列主機名的字符串,並在枚舉字符串之前先執行一系列命令。

那麼該腳本,讀了一系列主機名從txt文件在同一目錄下,然後將它們讀入一個字符串,.exp文件將自動登錄到每個他們與excecute系列的命令。

我有下面的代碼編寫的,但它不工作:

#!/usr/bin/expect 

set timeout 20 
set user test 
set password test 

set fp [open ./*.txt r] 
set scp [read -nonewline $fp] 
close $fp 

spawn ssh [email protected]$host 

expect "password" 
send "$password\r" 

expect "host1" 
send "$scp\r" 

expect "host1" 
send "exit\r" 

任何幫助是極大的讚賞....

+0

我有點困惑。你有一個文件列出所有的命令,另一個列出所有的主機?還是你有一個目錄,每個主機有一個文件(由帶有.txt擴展名的主機名命名?),它包含要在該主機上運行的命令? –

+0

你好。我正在嘗試創建一個循環。首先讀取文件host.txt,其中包含我希望運行exp腳本的所有服務器。然後,在host.txt的eof時,將位於commands.txt文件中的命令複製並粘貼到每個主機中。 – Tony

+0

這也意味着在這個腳本expect命令將期望一些不同的主機,如$ host1->,$ host2->等.... – Tony

回答

8

的代碼應該將這兩個文件的內容讀入行列表中,然後迭代它們。它最終是這樣的:

# Set up various other variables here ($user, $password) 

# Get the list of hosts, one per line ##### 
set f [open "host.txt"] 
set hosts [split [read $f] "\n"] 
close $f 

# Get the commands to run, one per line 
set f [open "commands.txt"] 
set commands [split [read $f] "\n"] 
close $f 

# Iterate over the hosts 
foreach host $hosts { 
    spawn ssh [email protected] 
    expect "password:" 
    send "$password\r" 

    # Iterate over the commands 
    foreach cmd $commands { 
     expect "% " 
     send "$cmd\r" 
    } 

    # Tidy up 
    expect "% " 
    send "exit\r" 
    expect eof 
    close 
} 

您可以重構這一點與工人的程序或兩個,但是這是基本的想法。

2

我重構了一下:

#!/usr/bin/expect 

set timeout 20 
set user test 
set password test 

proc check_host {hostname} { 
    global user passwordt 

    spawn ssh [email protected]$hostname 
    expect "password" 
    send "$password\r" 
    expect "% "    ;# adjust to suit the prompt accordingly 
    send "some command\r" 
    expect "% "    ;# adjust to suit the prompt accordingly 
    send "exit\r" 
    expect eof 
} 

set fp [open commands.txt r] 
while {[gets $fp line] != -1} { 
    check_host $line 
} 
close $fp 
1

在這裏使用這兩種解決方案中的任何一種,我還會創建一個日誌文件,以便以後查看。在運行腳本後,可以很容易地解決任何問題,尤其是在配置數百個主機時。

地址:

LOG_FILE -a [日誌文件名]

您的循環之前。

乾杯,

ķ