shell脚本之登录多台远程服务器,为其添加用户,以及expect语法的详细解说

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主机:
在这里插入图片描述
来解释一下语法:
在这里插入图片描述
第二种:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值