Here Documents 结合expect的使用--(1)

作者: My熊猫眼 | 来源:发表于2019-10-10 22:06 被阅读0次

here documents的语法为:

cmd << delimiter   #  << 可以替换为 <<-    ,  delimiter 也可以加上单引号来使用;
   Here Document Content
delimiter        #此处的delimiter不能有任何其他字符;

其中,要注意如下知识点:

  1. 起始部分的delimiter 的前后空格,tab键都会被忽略;
  2. 结尾部分的delimiter, 其前面以及后面都不能够留任何字符,否则会有语法报错;
  3. 结合上面的特点1 以及 2, 所以建议delimiter的前后都不要有空格,tab.
  4. 起始部分的<<符号后面,可以追加符号'-', 这样 here documents 的每一行前面的tab 会被忽略,但是空格并不会被忽略;, 这样使用的目的是为了确保在shell脚本中,here documents的内容看起来更美观;
  5. 如果把起始部分的delimiter 加上 单引号 引用起来,那么在here documents 部分的内容中,变量不会被解析;这种情况也是使用比较多的,比如通过cat命令来生成另一个脚本,通常不希望把here documents content中的变量进行解析
  6. 如果没有使用单引号来 包括delimiter, 那么here documents content中的变量会被解析,比如位置参数$1, 以及脚本中的其他变量等

使用expect 命令来解决自动交互问题是非常广泛的,expect有自己独特的语法,可以写expect脚本来解决复杂的交互问题;但是很多时候,我们会需要在shell中通过调用expect脚本来解决交互问题;这时候就需要Here Documents 来帮忙;
在expect使用的时候,需要注意如下几点:

expect ... send ... 的语法结构使用的坑,对于下面的语法结构,有时候send命令并没有成功的执行,这是因为spawn产生的子进程而并不知道send已经结束
expect ...
send ...
更好的写法是:
expect ...
send ...
expect ...
也正是这个原因,所以expect一般在最后都会使用如下的结构:
expect eof
看如下的例子:

[root@localhost ~]# cat 1.sh 
#!/bin/bash
for i in `cat ./t.txt`
    do echo "===========Password change for ID: $i================="
    expect <<-EOF
                spawn passwd $i
                expect "assword:"
                send "$1\n"
                expect "assword:"
                send "$1\n"                      #在这里密码并没有send ;
                exit
EOF
done
#运行上述脚本得到的结果如下:并没有成功修改密码
[root@localhost ~]# bash 1.sh  testpwd
===========Password change for ID: root=================
spawn passwd root
Changing password for user root.
New password: 
BAD PASSWORD: The password is shorter than 8 characters
Retype new password: [root@localhost ~]# 

重新修改代码,加上 expect eof 语句, 结果如下:

[root@localhost ~]# cat 1.sh 
#!/bin/bash
for i in `cat ./t.txt`
    do echo "===========Password change for ID: $i================="
    expect <<-EOF
                spawn passwd $i
                expect "assword:"
                send "$1\n"
                expect "assword:"
                send "$1\n"
        expect eof
                exit
EOF
done

#如下的运行结果成功修改了密码
[root@localhost ~]# bash 1.sh testpwd
===========Password change for ID: root=================
spawn passwd root
Changing password for user root.
New password: 
BAD PASSWORD: The password is shorter than 8 characters
Retype new password: 
passwd: all authentication tokens updated successfully.

本文原创,转载请注明出处

相关文章

网友评论

    本文标题:Here Documents 结合expect的使用--(1)

    本文链接:https://www.haomeiwen.com/subject/fbkapctx.html