如何在运行另一个脚本时模拟用户交互

如何在运行另一个脚本时模拟用户交互

当我想运行一堆 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

相关内容