如何在運行另一個腳本時模擬用戶交互

如何在運行另一個腳本時模擬用戶交互

當我想運行一堆 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::期望。在嘗試了兩者之後,我更喜歡後者,因為我更熟悉 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

相關內容