zoukankan      html  css  js  c++  java
  • CentOS 通过 expect 批量远程执行脚本和命令

    我们有时可能会批量去操作服务器,比如批量在服务器上上传某个文件,安装软件,执行某个命令和脚本,重启服务,重启服务器等,如果人工去一台台操作的话会特别繁琐,并浪费人力。

    这时我们可以使用expect,向目标服务器上发送指令去实现批量操作。

    下面的例子将在centos上将一个文件,批量拷贝到其他服务商上,并执行相应的命令

     1. 在centos上安装expect

       

    yum install expect

    2. 编写expect脚本 copyfilebatch.sh

      下面的脚本将向内网IP为 192.168.0.102 至 192.168.0.112 的服务器分别拷贝一个rc.local文件,拷贝成功后,执行chmod命令,分别重启服务器

       

     1 #!/usr/bin/expect -f
     2 set password rootpassword
     3 
     4 for {set i 102} {$i <= 112} {incr i} {
     5     set ip "192.168.0.$i"
     6     puts "$ip"
     7     
     8     
     9     spawn ssh  -o StrictHostKeyChecking=no  $ip
    10     set timeout 3 
    11     expect "root@$ip's password:"
    12     set timeout 3 
    13     send "$password
    "
    14     set timeout 3 
    15     send "exit
    "
    16 
    17 
    18     spawn scp /home/install/rc.local root@$ip:/etc/rc.d/rc.local
    19     set timeout 3 
    20     expect "root@$ip's password:"
    21     set timeout 3 
    22     send "$password
    "
    23     set timeout 3 
    24     send "exit
    "
    25 
    26 
    27 
    28 
    29    spawn ssh root@$ip
    30 
    31    expect {
    32     "*yes/no" { send "yes
    "; exp_continue}
    33     "*password:" { send "$password
    " }
    34    }
    35    expect "#*"
    36 
    37    #要执行的命令
    38    send "chmod +x /etc/rc.d/rc.local
    "
    39    send "reboot
    "
    40    send  "exit
    "
    41 
    42    expect eof
    43 
    44 
    45 
    46 }

  • 相关阅读:
    与eolinker api集成
    为什么要用eolinker帮助API开发
    什么是Eolinekr
    使用Eolinker加快您的API开发
    java反射
    mybatis-查询过程
    mybatis初始化过程
    mybatis的插件分析
    web.xml中的ContextLoaderListener和DispatcherServlet区别
    css+js杂记
  • 原文地址:https://www.cnblogs.com/DevinZhang1990/p/12692449.html
Copyright © 2011-2022 走看看