shell免交互
Here Document免交互
语法格式
命令 <<标记
…
…
标记
[root@localhost ~]# cat <<eof //标记,字符由<<和自定义的字符组成,结尾的自定义字符必须一样才能识别
> wolrd
> eof
hello
wolrd
我们可以用免交互来写本地yum源
[root@localhost ~]# cat > yum.repo <<eof
> [test]
> name=test
> baseurl=file:///mnt
> enabled=1
> gpgcheck=0
> eof
[root@localhost ~]# cat yum.repo
[test]
name=test
baseurl=file:///mnt
enabled=1
gpgcheck=0
在自定义字符前面加一个-可以忽略制表符和空格然后输出
#!/bin/bash
cat <<eof
hello world
eof
cat <<-eof
hello world
eof
[root@localhost ~]# bash yum.repo
hello world
hello world
- 也可以用来定义变量
[root@localhost ~]# a=10
[root@localhost ~]# echo $a
10
[root@localhost ~]# aa=$(cat <<eof //变量替换
> $a
> eof
> )
[root@localhost ~]# echo $aa
10
[root@localhost ~]# aa=$(cat <<'eof' //不使用变量替换
$a
eof
)
[root@localhost ~]# echo $aa
$a
也可以在脚本中使用多行注释
#!/bin/bash
<<eof
注释一
注释二
eof
expect免交互
- 用于自动化控制和测试
- 用于解决shell脚本中交互相关的问题
需要安装两个
[root@localhost ~]# rpm -q expect
expect-5.45-14.el7_1.x86_64
[root@localhost ~]# rpm -q tcl
tcl-8.5.13-8.el7.x86_64
声明解释器使用expect命令
#!/usr/bin/expect //命令的绝对路径
spawn ssh root@192.168.3.2 //需要加spawn来完成命令
expect {
"password:" //需要匹配的字符,ssh需要输密码时候的前面字符
{ send "hb201314\r";} //想要输入的字符,需要加\r才能回车
}
interact //使操作台停在远程终端上
[root@localhost ~]# ./3.sh
spawn ssh root@192.168.3.2
root@192.168.3.2's password:
Last login: Sun Jun 13 15:02:11 2021 from 192.168.3.1
[root@server ~]#
- send向进程发送数据串,来模拟用户输入
- 当声明解释器是expect时,需要赋予执行权限用./来执行脚本,用bash执行会报错
当声明解释器是bash时怎么写
#!/bin/bash
expect -c " //需要用expect控制
spawn ssh root@192.168.3.2 //远程的主机ip
expect "password:" {send \"hb201314\r\"} //前面写需要匹配的字符,后面写需要输入的字符,且需要用""来引起来并将符号转义
expect "#" {send \"ifconfig ens33\r\"}
expect "#" {send \"exit\r\"}
expect xxx //结尾字符,随意的字符串
"
[root@localhost ~]# ./ssh.sh
spawn ssh root@192.168.3.2
root@192.168.3.2's password:
Last login: Sun Jun 13 14:59:08 2021 from 192.168.3.1
[root@server ~]# ifconfig ens33
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.3.2 netmask 255.255.255.0 broadcast 192.168.3.255
inet6 fe80::20c:29ff:fee5:4bad prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:e5:4b:ad txqueuelen 1000 (Ethernet)
RX packets 84 bytes 13216 (12.9 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 216 bytes 27743 (27.0 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
[root@server ~]# exit
登出
Connection to 192.168.3.2 closed.
- 后面跟exp_continue来实现多分支,用这个来实现\r的效果
expect {
"aaa" {send "AA";exp_continue}
"bbb" {send "BB";exp_continue}
"ccc" {send "CC"}
}