Day 32nd: Shell Programming Distribution system (expect)

Source: Internet
Author: User
Tags set time rsync

Small Q: patriotism means that you are a national of this country, and for this country, it should be compared to other

All countries have deeper feelings. --George Bernard Shaw


A: Preface

Today, some of the larger businesses use load balancing, sometimes because some programs change, or some bugs

To modify, if only a few machines, we have modified the program to copy the past, or rsync remote push a

, or share it online with NFS, but if there are dozens of hundreds of units, that method will be too cumbersome, I

We can use expect to achieve distribution tasks in bulk;

Expect: A software suite for automatic interactivity, a scripting language based on TCL, with simple syntax;

Function: Realize automatic login to remote machine and execute command automatically;

Combined with shell scripts, it can be fully automated;

Note: The use of key authentication without a password can also implement this function; no key, only the other account and password.

Installation: Yum install-y excpet

Two: Usage

1. #!/usr/bin/expect

hint what shell is used in the operating system script, and expect and bash win cmd are similar;

Note: This line is required on the first line of the script.

2. Set command

Used to set certain variables, or time-outs, such as set user "root" setting user to represent root

or set timeout 30 30 seconds after disconnecting; set timeout-l means never timeout

3. Spawn the command or script that will be executed

Spawn is a expect internal command that can be executed after entering the expect environment, if it is not installed expect or directly in

The default shell execution is not available, where he is not found; common usage is as follows:

Spawn ssh-l username telnet to this terminal

Spawn Rsync-av [email protected]:/tmp/1/tmp/sync the remote files.

Its main function is to add a shell to the SSH running process to pass the interactive instructions.

4. Expect "Password:"

is also an internal command, and he is the same as the shell internal command, meaning to determine whether the last output

A string containing "password:", which contains the immediately returned, otherwise waits according to the set time;

5. Send "command"

perform interactive actions, which are commands to be executed by the remote machine;

send "yes\r" input yes,\r indicates carriage return

assword: "{send" mima\r "} indicates that the end is Assword, enter Mima and return  

6. Interact

after execution, keep the interaction state, and then manually enter the command, similar to SU; if you do not have this sentence after logging in

Will exit, rather than stay on the remote terminal; After the login command, end

7. $ARGV parameter array

expect scripts can accept parameters that are passed from bash. can be obtained using [lindex $argv n]; for example:

Set passwd [lindex $argv 0] can be called below with $PASSWD

spawn ssh [email protected] $passwd when executed, enter the password later, than the password placed in the file security
8. Expect EOF

identifier indicating that the child process has ended, or if there is no EOF, it may exit before the child process has ended, or

After the completion of the process to stay in the remote terminal is not back out;

Three: simple Example ( Assume that you are using a 1.expect script in the current directory)

1. Automatic remote login, and execute the command, login does not exit

#! / usr / bin / expect

set host "" #IP of remote terminal
set passwd "123456" #Remote terminal root password

spawn ssh [email protected] $ host #log in remote

expect {#child process
"yes / no" {send "yes \ r"; exp_continue} # Yes / no is encountered after login. Enter yes
"assword:" {send "$ passwd \ r"} #Encounter the word assword, enter a variable, and press Enter
} ## continue continue to execute in-process commands; do not end the process, similar to the one in c
interact #Keep interacting, don't quit

After logging in, execute the command and then exit the script:

#! / usr / bin / expect #fixed usage
set user "root" #same as above
set passwd "123456"

spawn ssh [email protected] #Log in remotely, no IP is defined as a variable, the effect is the same

expect {
"yes / no" {send "yes \ r"; exp_continue}
"password:" {send "$ passwd \ r"}
                                            #Execute the following command after login
expect "] *" #represents] # or] $, and some system roots also use] $
send "touch /tmp/12.txt\r" # encountered] *, create a file, and press enter
expect "] *"
send "echo 1212> /tmp/12.txt\r" #redirect, enter
expect "] *"
send "exit \ r" #Exit the system  

Execute script:./1.expect >>> Enter

2. Passing parameters

#! / usr / bin / expect
set user [lindex $ argv 0] #Define parameter array variables
set host ""
set passwd [lindex $ argv 1] #Under the bash environment, that is, the command line input, the password is effectively protected
set cm [lindex $ argv 2] #Define a command variable for remote machine operation

spawn ssh [email protected] $ host

expect {
"yes / no" {send "yes \ r"}
"password:" {send "$ passwd \ r"}
expect "] *"
send "$ cm \ r" #The variables defined above are also entered in the local bash environment
expect "] *"
send "exit \ r"

Execute script:./1.expect root Password W

Note: The number of array parameters refers to the order in which the script input is executed

3. Automatically synchronize files

#! / usr / bin / expect
set passwd "123456"

spawn rsync -av [email protected]: / tmp / 12.txt / tmp / #rsync

expect {
"yes / no" {send "yes \ r"}
"password:" {send "$ passwd \ r"}
expect eof #The child process ends and returns to the local terminal

Execute script:./1.expect

4. Specify the host and the files to synchronize

#! / usr / bin / expect
set passwd "123456"
set host [lindex $ argv 1] #Define array parameters, input in the 2nd position, in order to understand the order
set file [lindex $ argv 0]

spawn rsync -av $ file [email protected] $ host: $ file #Push to remote
expect {
"yes / no" {send "yes \ r"}
"password:" {send "$ passwd \ r"}
expect eof

Execute script:./1.expect/tmp/12.txt

Four: Application examples

Need: The company website interface needs to change, the change good program to you, distributes it to those hundreds of servers?

Idea: Prepare a template machine, all server IP write into a file for call, write a shell call IP one by one, will call

IP to expect implementation of distribution, you can use other methods to achieve password synchronization, not to mention him;

Core: rsync-av--files-from=list.txt/[Email protected]:/

1. Implementation of the document distribution system

#! / usr / bin / expect #expect script

set passwd "123456"
set host [lindex $ argv 0]
set file [lindex $ argv 1]
spawn rsync -av --files-from = $ file / [email protected] $ host: / #Used to synchronize a batch of files

expect {
"yes / no" {send "yes \ r"}
"password:" {send "$ passwd \ r"}
expect eof
#! / bin / bash #shell script, set to
for ip in `cat ip.list` #for loop
     echo $ ip #print one by one for expect call
     ./1.expect $ ip list.txt #Execute the expect script, IP and files correspond to the above order
                                   #IP list file, set to list.txt

At this point, just execute the shell script, you can;

2. command batch execution script

#! / usr / bin / expect #expect script for shell script calls

set host [lindex $ argv 0]
set passwd "123456"
set cm [lindex $ argv 1]

spawn ssh [email protected] $ host

expect {
"yes / no" {send "yes \ r"}
"password:" {send "$ passwd \ r"}
expect "] *"
send "$ cm \ r"
expect "] *"
send "exit \ r"
#! / bin / bash #shell script, set to

for ip in `cat ip.list` #Still borrowed the IP list file above
     echo $ ip
     ./1.expect $ ip ‘w; free -m; ls / tmp" #The command inside the quotes corresponds to $ 1, cm.
done #Script call,

Execution only needs to execute the shell script to be able;


In fact, these batch operations above, are based on the same machine password the same situation, or do not make the batch;

Or we are generating a password list file, introducing I, the IP and password sequence one by one corresponds, but also a small

In addition, we can set the same password for all servers, but the security is not high ha,

We can call expect script, two days change a password ah, with our previous mkpasswd;

Day 32nd: Shell Programming Distribution system (expect)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.