8

私がやろうとしていることは次のとおりです。

  1. ファイルを作成します。このファイルは、同じディレクトリからファイル.expを読み取り*.txt、テキスト ファイル内のすべてのコンテンツを解析して、expect スクリプトの文字列変数に変換します。
  2. 一連のホスト名を含む文字列をループし、文字列が列挙されるまで一連のコマンドを実行します。

txtしたがって、スクリプトが行うことは、同じディレクトリ内のファイルから一連のホスト名を読み取り、それらを文字列に読み取ることです。.expファイルはそれぞれに自動ログインし、一連のコマンドを実行します。

次のコードを記述しましたが、機能しません。

#!/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 $user@$host

expect "password"
send "$password\r"

expect "host1"
send "$scp\r"

expect "host1"
send "exit\r"

どんな助けでも大歓迎です....

4

3 に答える 3

18

コードは、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 $user@host
    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
}

ワーカー プロシージャを 1 つまたは 2 つ使用して、これを少しリファクタリングすることもできますが、それが基本的な考え方です。

于 2013-07-17T10:35:26.367 に答える
5

少しリファクタリングします:

#!/usr/bin/expect

set timeout 20
set user test
set password test

proc check_host {hostname} {
    global user passwordt

    spawn ssh $user@$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
于 2013-07-15T19:50:10.463 に答える
1

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

追加:

log_file -a [ログファイル名]

あなたのループの前に。

乾杯、

K

于 2015-04-24T16:07:25.677 に答える