複数のサーバーからIQNの出力を取得しようとしています。次のエラーが発生します。
エラー出力
spawn /usr/bin/ssh VM2 | /usr/bin/cat /etc/iscsi/initiatorname.iscsi
root@VM2's password:
bash: -c: line 0: syntax error near unexpected token `|'
bash: -c: line 0: `| /usr/bin/cat /etc/iscsi/initiatorname.iscsi'
スクリプト
#!/bin/bash
HOSTS="VM2 VM3 VM4 VM1"
read -p "Password: " PASSWORD
for HOST in $HOSTS
do
expect -c "
spawn cat /etc/iscsi/initiatorname.iscsi
expect {
"*password:*" { send $PASSWORD\r;interact }
}
exit
"
done
私は何が間違っていましたか?
ベストアンサー1
まず第一に、私はあなたが達成したいものが何であるかをよく理解していません。
私が理解したのは、すべてのサーバーでこれをしたいということですcat /etc/iscsi/initiatorname.iscsi
。そうですか?
interact
しかし、なぜすべてのサーバーでこれを行うのですか?
各サーバーとファイルにログインする最初の問題の回避策を公開しますcat
。ソリューションを追加したい場合は、interact
ソリューションを編集できます。
expect
だからまずbash
。
したがって、プログラムの実行に使用されるbashスクリプトは次のようになります。このスクリプトは、パスワードが印刷または表示されないようにパスワードを求めるメッセージを表示します(直接実行するのは簡単ではありませんexpect
)。
#!/bin/bash
expect_script="./connect_to_many_hosts_and_cat_files.exp"
[ ! -f $expect_script ] && echo expect_script does not exist && exit 1
echo "Please enter a password:"
read -s password
$expect_script $password
今expect
スクリプト自体
#!/usr/bin/expect
if {$argc != 1} {
puts "please run expect script using bash script"
puts "that prompts for password"
exit
}
set password [lindex $argv 0]
# replace hosts names with your host names !!!
set hosts "host1 host2"
foreach host [ split $hosts " " ] {
set number_of_password_prompts($host) 0
puts "# "
puts "# ssh $host"
puts "# "
spawn ssh $host
expect {
# here I put password check, just in case password is wrong
# look a bit ugly, but better than nothing
"Password:" {
if { $number_of_password_prompts($host) == 0 } {
incr number_of_password_prompts($host)
puts "# "
puts "# Authenticating try $number_of_password_prompts($host)"
puts "# "
send "$password\r"
exp_continue
} else {
puts "# "
puts "# Password is wrong"
puts "# "
exit
}
}
# in case on host /bin/sh or /bin/bash
"$ " {
puts "# "
puts "# cat /etc/iscsi/initiatorname.iscsi"
puts "# "
send "cat /etc/iscsi/initiatorname.iscsi \r"
expect "$ "
}
# in case on host /bin/csh
"% " {
puts "# "
puts "# cat /etc/iscsi/initiatorname.iscsi"
puts "# "
send "cat /etc/iscsi/initiatorname.iscsi \r"
expect "% "
}
send "exit\r"
expect eof
close
}
}
最後に、chmod +x
両方のファイルを保護してください。他の方法でも Expect を実行できます。また、意図した場所が正しく配置されていることを確認してください。私としてはそうです/usr/bin/expect
。なぜなら、あなたは他の人になることができるからです。
重要なことがもう一つあります。expect
サーバーのプロンプトが重要だからです。もしそうなら、/bin/bash
条件を追加しました。$
その場合は、/bin/csh
条件を追加する必要があります%
。
$PS1
あなたのヒントやその他のヒントがどのように管理されているかを確認することが非常に重要ですssh
。プロンプトが次の場合、上記のスクリプトは機能しません。
user@host:~>
これが機能するには、条件を追加する必要があります。expect
"> " {
puts "# "
puts "# cat /etc/iscsi/initiatorname.iscsi"
puts "# "
send "cat /etc/iscsi/initiatorname.iscsi \r"
expect "> "
}
私はなぜ仕事がうまくいかないのかを調べるために何日も過ごしました。