2013-07-15 5 views
5

私は何をしようとしていることにある。読む文字列の中にファイルや期待にループを行うスクリプト

  1. は、同じディレクトリから*.txtファイルから読み込まれ、すべてのコンテンツを解析します.expファイルを作成しますテキストファイル内のexpectスクリプト内の文字列変数に変換します。
  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

私は少し混乱しています。すべてのコマンドを一覧表示するファイルが1つあり、すべてのホストがリストされていますか?または、そのホスト上で実行するコマンドを保持するホストごとに1つのファイル(.txt拡張子を持つhostnameという名前)を持つディレクトリがありますか? –

+0

こんにちは。私はループを作成しようとしています。 expスクリプトを実行したいすべてのサーバが入っているファイルhost.txtをまず読んでください。そして、host.txtのeofの間に、commands.txtファイルにあるコマンドをコピーして各ホストに貼り付けます。 – Tony

+0

これは、このスクリプトのexpectコマンドが、$ host1->、$ host2-> etc ...のようないくつかの異なるホストを期待することを意味します。 – Tony

答えて

8

コードでは、2つのファイルの内容を行のリストに読み込み、それらを繰り返し処理します。それはこのように終わる:

# 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と、このビットをリファクタリングができ、それが基本的な考え方です。

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

ここでは2つのソリューションのいずれかを使用して、後で表示できるログファイルも作成します。特に数百のホストを設定している場合は、スクリプトの実行後に問題のトラブルシューティングを容易にします。

追加:

LOG_FILE -a [ログファイル名]あなたのループの前に

乾杯、

K

関連する問題