系统相关
首页 > 系统相关> > Shell编程之免交互

Shell编程之免交互

作者:互联网

文章目录


一、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结束符

2.5 set

2.6 exp_continue

2.7 send_user

3.示例

3.1 远程其他主机

[root@localhost ~]# cat ssh.sh
#!/bin/bash

expect -c "
spawn ssh root@192.168.30.3
expect \"\(yes/no\)\" { send \"yes\r\" }
expect \"password:\" { send \"123456\r\" }
interact
"


[root@localhost ~]# bash ssh.sh
spawn ssh root@192.168.30.3
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.

root@192.168.30.3'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 root@192.168.30.4
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
"


标签:bash,Shell,192.168,编程,之免,send,expect,root,localhost
来源: https://blog.csdn.net/weixin_51720711/article/details/117911612