编程知识 cdmana.com

The learning of Linux expect language script

1、 The first line of the head must be this

#!/usr/bin/expect        ##### Defines what a Scripter is 

2、 Receiving parameters

set name [lindex $argv 0]
set name2 [lindex $argv 1]
puts $argvc
puts $argv0
expect eof
exit
#set  Meaning of assignment parameter 
#name  Parameter name , There is no need to add any symbol when setting , When calling this parameter later, you need to add $ Symbol ,$name
#[lindex $argv 0]  This is how parameters are written ,0 Represents the first parameter 
#puts  Output string 
#$argvc  The number of arguments 
#$argv0  file name 
# Finally, the identifier waiting to indicate the end of the child process eof, And then quit .( notes : This wait eof There must be , without eof, It's possible to exit before the child process is finished , Cause problems .)

# Execution format 
./test.exp  Parameters 0  Parameters 1

3、 Carry out orders

set timeout 5
spawn ssh test@172...
expect "*password*"
send “my_password\r”
interact
# These sentences are usually used together 
#set timeout  Is to set the expiration time , for example spawn Executive shell If the statement times out , There is no match for expect String , It will continue to execute the next statement 
#spawn  perform shell command , Meeting fork Out of a sub process execution 
#expect  After execution shell The string expected to be accepted after the command , Support regular matching 
#send  Indicates input , Remember to write \r, Enter to let the program execute 
# Imagine using it yourself ssh Log on to the server remotely to understand what it means , End of input ip After the address , You need to enter the password manually , use expect Can be done automatically 

##interact, After execution, the subprocess returns the user rights to the user , Will be located in the current child process , For example, when you're done with remote login , It must be staying on a remote server 

4、 Other grammatical formats

##switch
set color  [lindex $argv 0]
switch  $color  {
        apple {
                puts "apple is blue"
        }
        banana {
                puts "banana is yellow "
        }
}

##if
if { "$test" == "apple" } {
        puts "$test"
} else  {
        puts "not apple"
}

##for
for {set i 0} {$i<4} {incr i} {
        puts "$i"
}

##while
while {$i<4} {
        puts "$i"
        incr i
}

## Defined function 
proc test {} {
        puts "ok"
}

版权声明
本文为[FLYミ]所创,转载请带上原文链接,感谢

Scroll to Top