bash scriptスクリプトとの自動化インタラクション
3399 ワード
bashスクリプトの一部のコマンドが手動で入力してインタラクションする必要がある場合、スクリプトの自動化は行えません.たとえば、
通常は
もう1つのtelnetの例は、
ssh somehost
はユーザー名とパスワードを入力する必要があります.スクリプトはこのコマンドを実行すると、停止し、ユーザーの入力を待っています.単純なシナリオで、たとえばユーザーが一度だけ入力する必要がある場合、すなわち、一度にインタラクションする場合、直接このようにすることができます.# ... some directives here
# Remove the machine, confirming "y" when asked by docker-machine
echo 'y' | docker-machine rm default
# ... more directives here
通常は
expect
ツールが必要です.expect
を使用してsshログインを自動化する例は、次のとおりです.#timeout is a predefined variable in expect which by default is set to 10 sec
#spawn_id is another default variable in expect.
#It is good practice to close spawn_id handle created by spawn command
set timeout 60
spawn ssh $user@machine
while {1} {
expect {
eof {break}
"The authenticity of host" {send "yes\r"}
"password:" {send "$password\r"}
"*\]" {send "exit\r"}
}
}
wait
close $spawn_id
もう1つのtelnetの例は、
# Assume $remote_server, $my_user_id, $my_password, and $my_command were read in earlier
# in the script.
# Open a telnet session to a remote server, and wait for a username prompt.
spawn telnet $remote_server
expect "username:"
# Send the username, and then wait for a password prompt.
send "$my_user_id\r"
expect "password:"
# Send the password, and then wait for a shell prompt.
send "$my_password\r"
expect "%"
# Send the prebuilt command, and then wait for another shell prompt.
send "$my_command\r"
expect "%"
# Capture the results of the command into a variable. This can be displayed, or written to disk.
set results $expect_out(buffer)
# Exit the telnet session, and wait for a special end-of-file character.
send "exit\r"
expect eof