繁体   English   中英

如何将expect和shell脚本一起使用

[英]how to use expect and shell script together

我正在使用expect脚本和一些shell脚本命令,如下所示。

#!/usr/bin/expect
#!/bin/bash
spawn sudo mkdir -p /usr/lib/jvm1
expect "\[sudo\] password for hduser:"
send "cisco\r"

spawn sudo apt-get install openssh-client

但是上面的命令没有安装openssh-client。 它只显示命令。 并没有安装任何东西。

我在哪里做错了?

openssh-client安装上spawn之后,你必须expect一些东西,以便expect等待它。 此外, expect不会打扰任何事情,只会退出。 在这种情况下,我们可以等待eof确认安装已完成。

#!/usr/bin/expect
spawn sudo mkdir /usr/lib/jvm1
# This will match the ": " at the end. That is why $ symbol used here.
expect ": $"; # It will be more robust than giving as below 
  #expect "\[sudo\] password for hduser:" 
send "password\r"
#This will match the literal '$' symbol, to match the '$' in terminal prompt
expect "\\$"
spawn sudo apt-get install openssh-client
expect ": $"
send "password\r"
expect eof { puts "OpenSSH Installation completed successfully. :)" }

在上面的代码中,使用文字'$'的原因是终端提示的原因。操作的手动交互如下。

dinesh@VirtualBox:~$ sudo mkdir /usr/lib/dinesh7
[sudo] password for dinesh: 
dinesh@VirtualBox:~$ 

最后一行在终端中有$符号。 根据您的终端,您可以自定义提示。 您可能想知道为什么我们必须第二次发送密码。 请记住,它不是通常的终端,在终端关闭之前,为其他管理员操作提供管理员密码。 expect ,我们每次都会产生不同的sudo ,这就是给它一次的原因。

正如Andrew指出的那样,你不需要添加#! bash路径。

更新:expect ,默认超时为10 seconds 您可以使用set更改它,如下所示。

set timeout 60; # Timeout will happen after 60 seconds.

你需要在apt-get中传递-y,就像这样: spawn sudo apt-get install -y openssh-client

- 或者 - 期望安装提示并回答“Y”

此外,您不需要运行两个shell,只需#!/usr/bin/expect就足够了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM