他のスクリプトの実行中にユーザー対話をシミュレートする方法

他のスクリプトの実行中にユーザー対話をシミュレートする方法

複数のLinuxコマンドを実行したい場合はうまくいきますが、他のスクリプトが呼び出されて実行時に入力を要求するときにユーザーに入力をどのように提供しますか?私は教室に同じサーバー設定を頻繁にインストールするので、それを完全に自動化したいと思います。

#!/bin/bash
sudo apt-get install python -y
sudo apt-get install python-m2crypto -y
sudo apt-get install git-core -y
git clone https://github.com/learningequality/ka-lite.git
cd ka-lite/
./setup_linux.sh

#the script works until here
#now, while the setup script is running, the following needs to happen
#I need to press enter twice
#enter the password twice
#press enter twice
#press y and then enter

#here are some things I tried, none of them worked
send "yes\n"
send "yes\n"
#echo | <Press [enter] to continue...> #enter
#echo | <return> #enter
Password8 #password
Password8 #password
echo | <yourfinecommandhere> #enter
echo | <return> #enter
y

ベストアンサー1

TCL Expectを使用するパール::期待する。両方を試した後、Perlに慣れているので、後者を好みます。

以下は、複数のテストサーバーへのSSH接続に使用するスクリプトの一部です(機密性の高い本番サーバーには推奨されません)。

if( defined $password ) {
  $exp->expect(
    $timeout,
    [   qr/no\)\?\s+$/i => sub {
        my $self = shift;
        $self->send("yes\n");
        exp_continue;
      }
    ],
    [   qr/password:\s+$/i => sub {
        my $self = shift;
        $self->send("$password\n");
        exp_continue;
      }
    ],
    '-re',
    qr/~/,    #' wait for shell prompt, then exit expect
  );
}

ここで完全なソースコードを見ることができます。https://github.com/DavidGamba/bin/blob/master/cssh

おすすめ記事