1、案例
(1)将文件作为命令的标准输入
格式:命令 < 文件
[root@server1 shells]# read ip pass < ip.txt //将变量ip和pass从文件ip.txt中读取
[root@server1 shells]# echo $ip //打印这两个变量,发现赋值成功
192.168.13.134
[root@server1 shells]# echo $pass
westos
read的普通用法:read 变量名
输入赋值
[root@server1 shells]# read o
westos //这部分是我输入的
[root@server1 shells]# echo $o
westos
(2)这时有好多主机和密码需要读入,因此需要使用循环
[root@server1 shells]# while read ip pass ;do echo $ip;echo $pass;done < ip.txt
192.168.13.134
westos
192.168.13.125
westos
我们发现很容易的就将所有的内容循环赋值给了变量。
(3)如何将expect编译器引入bash脚本中调用?
运用 <<EOF ......EOF
,将要写入expect编译器的命令行写入 <<EOF ......EOF
中:
代码如下:
#!/bin/bash
while read ip pass
do
/usr/bin/expect <<-EOF &> /dev/null //使用/usr/bin/expect编译器,从<<-EOF开始,到出现EOF结束,中间这段都为expect编译器使用。
spawn ssh root@$ip
expect {
"(yes/no)?" { send "yes\r";exp_continue }
"password:" { send "$pass\r" }
}
expect "#"
{ send "echo $?\ruseradd kongying\rexit\r" } //下面图片解说
expect eof
EOF //expect编译器调用结束
done < ip.txt
我将执行过程(/usr/bin/expect <<-EOF &> /dev/null)中导入空白的那部分&> /dev/null去掉了,这样中间脚本任何一个命令执行有错误,我们都能看出来,并且有助于加强对脚本的理解:
[root@server1 shells]# sh ssh.sh
spawn ssh root@192.168.13.134
root@192.168.13.134's password:
Last login: Wed Nov 11 15:31:41 2020 from 192.168.13.129
mount: /dev/sr0 is write-protected, mounting read-only
mount: /dev/sr0 is already mounted or /var/www/html/rhel7.5 busy
/dev/sr0 is already mounted on /var/www/html/rhel7.5
[root@server2 ~]# echo 0
0
[root@server2 ~]# useradd kongying
useradd: warning: the home directory already exists.
Not copying any file from skel directory into it.
Creating mailbox file: File exists
[root@server2 ~]# exit
logout
Connection to 192.168.13.134 closed.
spawn ssh root@192.168.13.125
root@192.168.13.125's password:
Last login: Wed Nov 11 10:23:39 2020 from 192.168.13.129
[root@localhost ~]# echo 0
0
[root@localhost ~]# useradd kongying
useradd: warning: the home directory already exists.
Not copying any file from skel directory into it.
Creating mailbox file: File exists
[root@localhost ~]# exit
logout
Connection to 192.168.13.125 closed.
来看看登录的主机:
192.168.13.134主机:
[root@server2 mnt]# id kongying
uid=1006(kongying) gid=1006(kongying) groups=1006(kongying)
192.168.13.125主机:
来解释一下语法:
第二种: