expectとは
LinuxやFreeBSDで利用できる、sshやSQL等、対話的な通信を自動化するツールです。
expectでsshするサンプル
sshで接続して、lsを実行。
#!/usr/bin/expect set timeout 5 spawn ssh somehost.example.com expect "password:" send "YOUR PASSWD\r" expect "Last login" send "ls\r" interact
expectでメールを送信するサンプル
sendmailをexpectで叩いてメール送信。テスト送信を何回もやるとき便利。
#!/usr/bin/expect set timeout 5 spawn telnet somehost.example.com 25 expect "somehost.example.com" send "helo somehost.example.com\n" expect "pleased to meet you" send "mail from:someone@someplace.example.com\n" expect "Sender ok" send "rcpt to:yourfriend@somehost.example.com\n" expect "Recipient ok" send "data\n" expect "itself" send "This is Message for TEST\n" send ".\n" expect "accepted for delivery" send "quit\n"
expect のコマンド一覧
| コマンド | 説明 |
|---|---|
| set timeout N | タイムアウトを設定する(単位は秒) 設定したN秒以上、標準入力から応答がないと、expectは通信を終了する。 -1で、タイムアウトをナシにできる。 |
| spawn command | spawnは新しいジョブを作成し、expectプログラムの 入出力をそのジョブに接続する。 ジョブへの送信はsend、受信はexpectとなる。 |
| expect 文字列 | expectコマンドは標準入力データが正規表現での文字列に マッチするまで次のプログラム行の実行を停止し、データを標準出力に出力します。 |
| send 文字列 | 文字列をジョブへ出力します |
| interact | interactはspawnで作成されたジョブの標準入出力を、キーボードと画面にする。 すなわち通常の通信になる。 |
参考文献
|
|


