Shell script without interaction

Directory

1. Here Document is interactive free

1) The concept of interaction and its application in Linux

2) The role and format of Here Doucument

3) Application of Here Document

①Reading of the read command

②The statistics of the number of lines of content of wc -l

③Modification of passwd user password

④cat View content and input content to file without interaction

⑤ tee command redirection output plus standard output

2. Use of Here Document variables

1) Operation of output variables in interactive content

2) Variable operations are not output in interactive content

3) Multi-line comments

4) Remove the influence of the tab key

3. Expect realizes interaction-free application

1) Introduction to the Expect tool

2) Detect whether the Expect tool exists and how to install it

3) Basic usage of Expect

① Declaration of script interpreter

②spawn starts the process and captures interactive information

③expect receives a string from the process

④send is used to send a string to the process

⑤ terminator (expect eof and interact can only choose one)

⑥set Set the session timeout

⑦exp_continue

⑧send_users

⑨ Receive parameters

4. Expect interactive script application

Example: Interaction-free presets modify user passwords

original interactive process

script writing

Result presentation

Example: passing in and obtaining values through location variables, and modifying user passwords

Result presentation

Example: Modify user password in embedded execution mode

Result presentation

Example: su command to switch users

original interactive process

script writing

Result presentation

?edit

Example: ssh remote login

original interactive process

script writing

Results of the

Example: fdisk partition operation

original interactive process

script writing

Results of the


1. Here Document Free Interaction

1) The concept of interaction and its application in Linux

Interaction: When the computer plays a certain multimedia program, the programmer can issue instructions to control the operation of the program, instead of the program being executed unilaterally, the program will respond accordingly after receiving the corresponding instruction from the programmer. React.

For the Linux operating system, there are many operations that involve interaction (according to the instructions of the system to make corresponding operations to meet the needs of the operator), for the automated operation and maintenance of shell scripts, it is necessary to achieve interaction-free to achieve automated operation and maintenance Effect

Commonly used interactive programs: read, ftp, passwd, su, sudo, fdisk, etc.

cat can also redirect output to a file in a non-interactive way

2) Function and format of Here Doucument

The role of Here Document:

  • Use I/O redirection to provide command lists to interactive programs
  • An alternative to standard input
grammar format:

command << start tag

...................................

................................

closing tag

Instructions for use:

  • The tag can use any legal characters, but the opening and closing tags need to be consistent. (Common mark EOF, other letters can also be used)
  • The tag at the end must be written in the top case, and there cannot be any characters in front
  • The closing tag also cannot have any characters (including blank lines)
  • Spaces before and after the opening tag will be omitted

3) Application of Here Document

①Reading of the read command

[root@localhost jiaohu]#read a <<EOF
> this is a test
> hello world
> EOF
[root@localhost jiaohu]#echo $a
 
[root@localhost jiaohu]#read a <<jiewei
> this is a test2
> jiewei
[root@localhost jiaohu]#echo $a

②wc -l content line statistics

[root@localhost jiaohu]#wc -l <<EOF
> aaaaa
> bbbbb
> ccccc
> ddddd
> eeeee
> ddddd
> EOF

③passwd user password modification

[root@localhost jiaohu]#passwd <<EOF
> 12341234
> 12341234
> EOF

④cat view content and input content to file without interaction

cat view interactive input content

[root@localhost jiaohu]#cat <<EOF
> my name is zhangsan
> hello world
> EOF

cat to view interactive content and output to a new file

[root@localhost jiaohu]#cat <<EOF>test.txt
> hello world
> i im zhangsan
> EOF
[root@localhost jiaohu]#cat test.txt 

⑤tee command redirection output plus standard output

[root@localhost jiaohu]#tee test2.txt <<EOF
> this is tee test
> EOF
this is tee test
[root@localhost jiaohu]#cat test2.txt

2. Use of Here Document variables

Here Document also supports the use of variables

If a variable is used between tags, it will substitute the variable value first. If you want to write some content to a file, in addition to the normal method, you can also use Here Document

If the written content contains variables, replace the variables with actual values when writing the file, and then combine the cat command to complete the output

1) Operation of output variables in interactive content

#!/bin/bash
 
var="this is test1"
 
var1=$(cat <<EOF
this is test2
this is test3
$var
EOF
)
echo "$var1"

Output result:

2) Do not output variable operations in interactive content

#!/bin/bash
 
var="this is test1"
 
var1=$(cat <<'EOF'
this is test2
this is test3
$var
EOF
)
echo "$var1"

Output:

3) Multi-line comment

Here Document starting with a colon is a multi-line comment. The entered content will not be executed. (It is more intuitive to use # to comment)

4) Remove the influence of the tab key

Output:

Workaround:

#!/bin/bash
 
cat <<-EOF
                                        this is a test3
EOF
 

Output:

3. Expect realizes interaction-free application

1) Introduction to Expect Tool

Expect is a tool based on the tcl language. It is often used for automated control and testing, and to solve interaction-related problems in shell scripts.

Two packages need to be installed: expect, tcl. But after installing expect, there will be tcl (yum will install tcl after resolving dependencies)

A tool based on the tcl language, often used for automated control and testing, to solve interaction-related problems in shell scripts

2) Detect the existence and installation method of the Expect tool

#Check the expect installation package:

rpm -q expect

#Check the dependency package tcl:

rpm -q tcl

#Install and download the expect tool:

yum install -y expect #Install expect (tcl package will be installed as a dependency)

3) Basic usage of Expect

①Declaration of script interpreter

In the expect script, the file is first introduced, indicating which shell is used

spawn start process and capture interaction information

spawn is usually followed by a Linux execution command, which means opening a session, starting a process, and tracking subsequent interaction information

expect to receive a string from a process

  • Judge whether the last output result contains the specified string, if so, return immediately, otherwise wait for the timeout and return
  • Can only capture output from processes started by spawn
  • Used to receive the output after the command is executed, and then match the expected string

④send is used to send a string to the process

  • Send a string to the process to simulate user input
  • This command cannot automatically return and line feed, generally add \r (carriage return) or \

⑤ terminator (you can only choose one of expect eof and interact)

1) expect eof

  • Indicates that the interaction is over, wait for the execution to end, and return to the original user, corresponding to spawn.
  • For example, when switching to the root user, the expect script waits for 10s by default. After the command is executed, it stays for 10s by default and then automatically switches back to the original user.

2) interact

  • Keep the interactive state after execution, and give the control to the console to stay in the target terminal instead of returning to the original terminal. At this time, you can manually operate, and the command after interact will not work
  • Using interact will stay in the terminal without returning to the original terminal

⑥set set session timeout

expect The default timeout is 10 seconds, the session timeout can be set through the set command, if there is no timeout limit, it should be set to -1

⑦exp_continue

  • exp_continue is appended to an expect judgment item, so that after the item is matched, it can continue to match other items in the expect judgment statement
  • exp_continue is similar to the continue statement in the control statement. Indicates that expect is allowed to continue to execute instructions
  • Parallel execution, if there is a match before exp_continue, it will be executed, if there is no match, it will not be executed; but the latter will definitely be executed

send_users

Indicates the echo command, which is equivalent to echo

⑨Receive parameters

The expect script can accept arguments passed from the bash command line, obtained using [lindex $argv n]. Among them, you start from 0, which means the first, second, third…..parameters

Fourth, Expect interaction-free script application

Note: The expect script cannot be executed through bash, source, and . (because these three methods call the shell interpreter), it can only be executed through an absolute path or a relative path

Example: Change user password by default value without interaction

Original interaction process

scripting

#!/usr/bin/expect
 
#This script is used to modify the password of zhangsan user without interaction
 
set timeout 5
 
spawn passwd zhangsan
 
expect "new password"
send "123abcd\r"
expect "Re-enter new password"
send "123abcd\r"
 
expect eof

Result presentation

Example: Pass in the obtained value through the position variable, modify the user password

Result presentation

Example: Modify user password in embedded execution mode

Embedded execution mode integrates the expect process into the shell, which is convenient for execution and processing; however, it is generally not recommended to use embedded execution mode for interactive commands like ssh and su that switch environments

#!/bin/bash
username=$1
password=$2
/usr/bin/expect << EOF
set timeout 5
spawn passwd $username
expect "new password"
send "$password\
"
expect "Re-enter new password"
send "$password\
"
 
expect eof
EOF

Result presentation

Example: su command to switch users

Original interaction process

Scripting

#!/usr/bin/expect
 
set timeout 1
 
set username [ lindex $argv 0 ]
set password [ lindex $argv 1 ]
 
spawn su $username
expect "password"
send "$password\
"
 
expect "*]#"
send_user "$username switched successfully!"
 
interact

Result presentation

Example: ssh remote login

Original interaction process

scripting

#!/usr/bin/expect
 
set timeout 5
set hostname [ lindex $argv 0 ]
set password [ lindex $argv 1 ]
 
spawn ssh $hostname
expect {
 "No route to host" exit
 "Connection refused" exit
 "(yes/no)" {send "yes\
" ; exp_continue}
 "password:" {send "$password\
"}
}
interact

execution result

Example: fdisk partition operation

Original interaction process

Scripting

#!/usr/bin/expect
 
set timeout 5
set name [lindex $argv 0]
            
spawn fdisk $name
expect "get help"
send "n\r"
expect "Select"
send "p\r"
expect "partition number"
send "\r"
expect "Start"
send "\r"
expect "Last"
send " + 10G\r"
expect "command"
send "w\r"
    
interact

Execution results

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge Cloud native entry skill treeHomepageOverview 12807 people are studying systematically