expect+正则

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/qq_41729148/article/details/89092449

expect可以实现自动处理输入和输出的功能。

安装:
yum -y install expect
简单使用:
#!/usr/bin/expect
指定脚本使用的shell
set timeout 30
设置超时时间为30s
spawn 
用来给ssh运行加个壳
expect
用于判断输出结果是否包含某项字符串,没有立即返回,否则经过timeout时间返回。
send
执行交互的动作
exp_continue
继续执行接下来的交互操作
interact
执行完保存交互的状态,不加就会自动退出
$argv 
接受参数

实例:免密码通过ssh登录服务器

#!/usr/bin/expect
set ipaddr "192.168.1.64"
set name "root"
set passwd "du19991221"
set timeout 30
spawn ssh $name@$ipaddr
expect {
"yes/no" { send "yes\r"; exp_continue }
"password" { send "$passwd\r" }
}
expect "#"
send "echo hello world\r"
interact

在这里插入图片描述
正则表达式

字符 含义
$ 字符串的结尾位置
() 标记字符串的开始和结束
* 匹配0次或者多次
+ 匹配1次或者多次
匹配0次或者1次
. 匹配\n之外的任意一个单字符
| 转义
^ 匹配开头
\n 换行
\r 回车
\t 制表符

小例子:可以查看服务的配置文件中真正的内容。

[root@break ~]# grep -v "^$\|^#" /etc/ssh/sshd_config 
[root@break ~]# grep -vE "^$|^#" /etc/ssh/sshd_config 
[root@break ~]# egrep -v "^$|^#" /etc/ssh/sshd_config 

在这里插入图片描述

bash进行查看shell的流程

x:查看执行的详细过程
v:查看bash是否存在语法错误
bash -v while-1.sh
bash -x while-1.sh

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41729148/article/details/89092449