CentOS Batch remote execution of scripts and commands using expect

  • 2021-08-12 04:22:32
  • OfStack

Sometimes we may operate servers in batches, such as uploading a file on the server in batches, installing software, executing a command and script, restarting services, restarting servers, etc. It will be particularly cumbersome and waste manpower if we manually operate one by one.

In this case, we can use expect to send instructions to the target server to implement batch operation.

The following example will copy 1 file to other service providers in batches on centos and execute the corresponding commands

1. Install expect on centos

yum install expect

2. Write the expect script copyfilebatch. sh

The following script copies one rc. local file to the servers on the intranet IP 192.168. 0.102 to 192.168. 0.112 respectively. After successful copying, execute the chmod command to restart the servers respectively


#!/usr/bin/expect -f
set password rootpassword

for {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 "#*"

  # Command to execute 
  send "chmod +x /etc/rc.d/rc.local\r"
  send "reboot\r"
  send "exit\r"
  expect eof
}

Related articles: