文章目录
一、Here Document
1.概述
命令 <<标记
...
...
标记
2.使用注意事项
3.示例
3.1 直接修改密码
[root@localhost ~]# useradd zhangsan
[root@localhost ~]# passwd zhangsan <<EOF
> 123
> 123
> EOF
更改用户 zhangsan 的密码 。
新的 密码:无效的密码: 密码少于 8 个字符
重新输入新的 密码:passwd:所有的身份验证令牌已经成功更新。
[root@localhost ~]#
3.2 忽略制表符
[root@localhost ~]# bash test.sh
123
321
[root@localhost ~]# cat test.sh
#!/bin/bash
cat <<EOF
123
321
EOF
[root@localhost ~]# bash test.sh
123
321
[root@localhost ~]# cat test.sh
#!/bin/bash
cat <<-EOF //-使制表符失效
123
321
EOF
[root@localhost ~]# bash test.sh
123
321
[root@localhost ~]#
3.3 多行注释
[root@localhost ~]# cat test.sh
#!/bin/bash
<<hl
cat <<-EOF
123
321
EOF
hl
echo 123
[root@localhost ~]# bash test.sh
123
[root@localhost ~]#
二、Expect
1.概述
2.基本命令
2.1 expect
2.2 send
2.3 spawn
- 启动进程,并跟踪后续交互信息
2.4结束符
- expect eof (等待执行结束)
- interact (执行完成后保持交互状态,把控制权交给控制台)
2.5 set
- 设置超时时间,过期则继续执行后续指令
- 默认,timeout事10s
2.6 exp_continue
- 允许expect继续向下执行指令
2.7 send_user
- 回显命令,相当于echo
3.示例
3.1 远程其他主机
[root@localhost ~]# cat ssh.sh
#!/bin/bash
expect -c "
spawn ssh [email protected]
expect \"\(yes/no\)\" { send \"yes\r\" }
expect \"password:\" { send \"123456\r\" }
interact
"
[root@localhost ~]# bash ssh.sh
spawn ssh [email protected]
The authenticity of host '192.168.30.3 (192.168.30.3)' can't be established.
ECDSA key fingerprint is SHA256:396BF852ITFX9y8B/HTvPAeICxxYzk4Wc7o8nWgyIQ4.
ECDSA key fingerprint is MD5:75:63:23:ba:73:cc:5d:4d:e6:2a:6a:9b:c3:71:43:a7.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.30.3' (ECDSA) to the list of kNown hosts.
[email protected]'s password:
Last login: Mon Jun 14 19:26:25 2021 from 192.168.30.254
[root@localhost ~]#
3.2 无交互使得另一台主机的新磁盘挂载
[root@localhost ~]# cat fdisk.sh
#!/bin/bash
expect -c " //在bash环境下调用expect
spawn ssh [email protected]
expect \"password:\" { send \"123456\r\"}
expect \"]#\" { send \"fdisk /dev/sdb\r\"}
expect \"):\" { send \"n\r\"}
expect \"):\" { send \"p\r\"}
expect \"):\" { send \"\r\"}
expect \"):\" { send \"\r\"}
expect \"):\" { send \"\r\"}
expect \"):\" { send \"w\r\"}
expect \"]#\" { send \"mkdir /data\r\"}
expect \"]#\" { send \"mkfs.xfs /dev/sdb1\r\"}
expect \"]#\" { send \"mount /dev/sdb1 /data\r\"}
expect \"]#\" { send \"df -h\r\"}
expect eof
"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。