shell 脚本中交互输入自动化 您所在的位置:网站首页 sheel脚本执行命令 shell 脚本中交互输入自动化

shell 脚本中交互输入自动化

2024-01-02 11:20| 来源: 网络整理| 查看: 265

最近写自动安装脚本遇到redis-server安装的时候,需要输入3个回车,对此尝试无果,最后google比较满意的解决办法:

shell 脚本需要交互,比如输入回车,输入YES/NO Y/N之类进行选择

Linux 中shell脚本运行时经常需要进行交互,比如安装软件的过程中对license声明的确认,需要输入yes,回车之类的确认信息。这个在自动化安装的时候就会是个问题。

1、通常对于这个问题比较灵活的解决方法就是TCL的Expect。但Expect还需要另外安装,平台通用性不高,比较麻烦。 2、另外一些简单的方法倒也是有,不过可用性不高,特别是对要求多次交互就吃力了。但怎么说其还是能解决大多数的问题,因为复杂的情况还是比较少的。 比如要一个调用一个安装脚本: installWAS.sh, 这个脚本要求输入回车, 则可以:echo | installWAS.sh; 如果要求输入yes|no,加回车,则可以 echo yes|installWAS.sh 这下自动化安装就有希望了。 1、利用重定向

例:以下的test.sh是要求我们从stdin中分别输入no,name然后将输入的no,name打印出来

root@localhost test]# cat test.sh #! /bin/bash read -p "enter number:" no read -p "enter name:" name echo you have entered $no, $name #以下是作为输入的文件内容: [root@localhost test]# cat input.data 1 lufubo #然后我们利用重定向来完成交互的自动化: [root@localhost test]# ./test.sh < input.data you have entered 1, lufubo 2、利用管道完成交互的自动化

这个就是利用管道特点,让前个命令的输出作为后个命令的输入完成的 也用上面例子举例:

[root@localhost test]# echo -e "1\nlufbo\n" | ./test.sh you have entered 1, lufbo

上面中的 "1\nlufbo\n"中的\n是换行符的意思,这个比较简单的。

3、利用expect

expect是专门用来交互自动化的工具,但它有可能不是随系统就安装好的,有时需要自己手工安装该命令

查看是否已经安装:rpm -qa | grep expect

以下脚本完成跟上述相同的功能

[root@localhost test]# cat expect_test.sh #! /usr/bin/expect spawn ./test.sh expect "enter number:" send "1\n" expect "enter name:" send "lufubo\n" expect off

注意: 第一行是/usr/bin/expect,这个是选用解释器的意思,我们shell一般选的是 /bin/bash,这里不是

spawn: 指定需要将哪个命令自动化 expect: 需要等待的消息 send: 是要发送的命令 expect off: 指明命令交互结束

最后具体实现: [root@localhost opt]# cat cache.sh #!/bin/bash yum install -y gcc-c++ tcl cd /opt #cache wget http://download.redis.io/releases/redis-3.0.0.tar.gz #------------------------------------------------------------------------------------# #编译源程序 tar xf redis-3.0.0.tar.gz cd redis-3.0.0 make && cd src && make install cd /opt/redis-3.0.0/utils echo | /bin/bash install_server.sh mv /etc/redis/6379.conf /etc/redis/redis.conf mv /etc/init.d/redis_6379 /etc/init.d/redis sed -i "[email protected]@redis.conf@" /etc/init.d/redis sed -ine "65s/# bind 127.0.0.1/bind 0.0.0.0/" /etc/redis/redis.conf sed -ine "393 i\requirepass Bs123456A" /etc/redis/redis.conf #默认情况下,redis不是在后台运行的,我们需要把开启的redis后台运行,将daemonize的值改为yes echo "vm.overcommit_memory=1">>/etc/sysctl.conf sysctl -p 参考文档:

linux shell执行中需要交互输入回车,Yes/NO Y/N

shell中交互输入自动化



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有