广州明生堂生物科技有限公司


CentOS xhsell expect批量远程执行脚本和命令

网络编程 CentOS xhsell expect批量远程执行脚本和命令 09-20

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

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

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

1. 在centos上安装expect

yum install expect

2. 编写expect脚本 copyfilebatch.sh

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

#!/usr/bin/expect -fset password rootpasswordfor {set i 102} {$i <= 112} {incr i} {  set ip "192.168.0.$i"  puts "$ip"  spawn ssh -o StrictHostKeyChecking=no $ip  set timeout 3  expect "root@$ip's password:"  set timeout 3  send "$password\r"  set timeout 3  send "exit\r"  spawn scp /home/install/rc.local root@$ip:/etc/rc.d/rc.local  set timeout 3  expect "root@$ip's password:"  set timeout 3  send "$password\r"  set timeout 3  send "exit\r"  spawn ssh root@$ip  expect {  "*yes/no" { send "yes\r"; exp_continue}  "*password:" { send "$password\r" }  }  expect "#*"  #要执行的命令  send "chmod +x /etc/rc.d/rc.local\r"  send "reboot\r"  send "exit\r"  expect eof}

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

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

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

1. 在centos上安装expect

yum install expect

2. 编写expect脚本 copyfilebatch.sh

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

#!/usr/bin/expect -fset password rootpasswordfor {set i 102} {$i <= 112} {incr i} {  set ip "192.168.0.$i"  puts "$ip"  spawn ssh -o StrictHostKeyChecking=no $ip  set timeout 3  expect "root@$ip's password:"  set timeout 3  send "$password\r"  set timeout 3  send "exit\r"  spawn scp /home/install/rc.local root@$ip:/etc/rc.d/rc.local  set timeout 3  expect "root@$ip's password:"  set timeout 3  send "$password\r"  set timeout 3  send "exit\r"  spawn ssh root@$ip  expect {  "*yes/no" { send "yes\r"; exp_continue}  "*password:" { send "$password\r" }  }  expect "#*"  #要执行的命令  send "chmod +x /etc/rc.d/rc.local\r"  send "reboot\r"  send "exit\r"  expect eof}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


编辑:广州明生堂生物科技有限公司

标签:批量,重启,命令,服务器,脚本