shell programming interaction free command

Posted by febrarian on Mon, 17 Jan 2022 16:06:36 +0100

shell programming interaction free command

Article catalog

1, Here Document interaction free

Use I/O redirection to provide a list of commands to interactive programs or commands, such as ftp, cat, or read commands.
It is an alternative to standard input, which can help script developers not use temporary files to build input information, but directly generate a "file" in place and use it as standard input for "commands". Here Document can also be used with non interactive programs and commands.

Syntax format:
command <<sign
...
content    #Tags are directly incoming content
...
sign

 

    matters needing attention:
    Tags can use any legal character (usually EOF)
    The mark at the end must be written in the top grid and cannot be preceded by any characters
    There must be no characters (including spaces) after the tag at the end
    Spaces before and after the opening mark are omitted

    1. The number of rows is counted in an interactive way. The content to be counted is placed between the "EOF" tags, and the content is directly transmitted to wc -l for statistics

    wc -l <<EOF
    >Line1
    >Line2
    >EOF
    
     

      2. The input is received and printed through the read command. The input value is the part between the two EOF tags as the value of variable i

      read i <<EOF
      >Hi
      >EOF
      echo $i
      
       

        3. Set the password for the user through passwd

        passwd list <<EOF
        >abc123123            
        >abc123123
        EOF
        
         

          4. Support variable replacement
          When writing a file, the variable will be replaced with the actual value, and then the writing will be completed in combination with the cat command

          #!/bin/bash
          file="eof1.txt"
          i="school"
          cat > $file <<EOF
          I am going to $i
          EOF
          
           


            5. Assign the whole value to the variable, and then print the variable value through the echo command

            #!/bin/bash
            var="Great! I am going to school!"
            myvar=$(cat <<EOF
            This is Line 1.
            Today is Monday.
            $var
            EOF
            )
            echo $myvar
            
             


              6. Turn off the function of variable replacement and output the characters as they are without any modification or replacement

              #!/bin/bash
              var="Great! I am going to school!"
              myvar=$(cat <<'EOF'
              This is Line 1.
              Today is Monday.
              $var
              EOF
              )
              echo $myvar
              
               


                7. Remove the TAB character before each line

                #!/bin/bash
                var="Great! I am going to school!"
                myvar=$(cat <<-'EOF'        #Add "-" before the mark to suppress the tab characters in each line
                       This is Line 1.
                       Today is Monay.
                       $var
                EOF
                )
                echo "$myvar"
                
                 

                  8. Multiline comment
                  Bash's default annotation is "#". This annotation method only supports single line annotation: the introduction of Here Document solves the problem of multi line annotation.
                  ":" represents an empty command that does nothing. The contents of the middle mark area will not be executed and will be ignored by bash, so the effect of batch annotation can be achieved.

                  #!/bin/bash
                  var="Great! I am going to school!"
                  : <<-EOF      
                  This is Line1.
                  Today is Monday.
                  $var
                  EOF
                  echo "abcd"
                  
                   


                    2, Expect

                    A tool based on tcl language is often used for automatic control and testing to solve the problems related to interaction in shell scripts.

                    rpm -q expect
                    rpm -q tcl
                    yum -y install expect
                    
                     
                    • 1. Basic command

                      (1) Script interpreter
                      The expect script first introduces a file to indicate which shell is used

                      #!/usr/bin/expect
                      
                         

                      (2)spawn
                      spawn is usually followed by a Linux execution command to start a session, start a process, and track subsequent interaction information.
                      Example:

                      spawn passwd root
                      
                       

                        (3)expect
                        Judge whether the last input result contains the specified string. If so, it will be returned immediately. Otherwise, it will be returned after the timeout: it can only capture the output of the process started by spawn;
                        It is used to receive the output after the command is executed, and then match the expected string

                        (4)send
                        Send a string to the process to simulate the user's input; This command does not automatically enter or wrap. Generally add \ R (enter) or \ n

                        Example:
                        Mode 1:

                        expect ""Password" {send "abc123\r"}   #The send part of the same line should be composed of {}
                        
                         

                          Mode 2:

                          expect ""Password"
                          send "$abc123\r"         #The newline send part does not need to have {}
                          
                           

                            Mode 3:

                            expect "Support multiple branches
                            

                            Expect {# as long as one of the cases is matched, execute the corresponding send statement and exit the expect statement
                            "Password 1 {send" abc123\r "}"
                            "Password 2 {send" 123123\r "}"
                            "Password 3 {send" 123123\r "}"
                            }

                              (5) Terminator
                              expect eof
                              Indicates the end of interaction, waits for the end of execution, and returns to the original user, corresponding to spawn
                              For example, when switching to the root user, the expect script waits for 10s by default. After executing the command, it stays for 10s by default and automatically switches back to the original user

                              interact
                              After the execution is completed, keep the interactive state, hand over the control to the console and stay at the target terminal. At this time, you can operate manually. The commands after the interaction do not work. For example, the interaction will remain at the terminal and will not return to the original terminal. For example, if you switch to the root user, it will always be in the root user state; For example, ssh to another server will always be on the target server terminal without switching back to the original server.

                              Note: only one of expect eof and interact can be selected

                              (6)set
                              The default timeout of expect is 10 seconds. You can set the session timeout through the set command. If the timeout is not limited, it should be set to - 1
                              Example: set timeout 30

                              (7)exp_continue
                              exp_ After continue is attached to an expect judgment item, you can continue to match other items in the expect judgment statement after the item is matched. exp_continue is similar to the continue statement in a control statement. Indicates that expect is allowed to continue to execute instructions downward

                              The following example will determine whether yes/no or * password exists in the interactive output. If yes/no is matched, yes is output and the judgment is performed again; If * assword matches, output abc123 and end the expect statement.

                              expect
                              "(yes/no)" {send "yes\r"; exp_ continue; }
                              "*password" {set timeout 300; send "abc123\r";}
                              
                               
                              • Note: use exp_ During continue, if you follow the command such as passwd that ends the process after entering the password, do not add expect eof to expect {}
                                Because after the spawn process ends, eof will be sent to expect by default, which will lead to an error in the subsequent expected eof execution
                                (8) send_ user
                                send_ user means echo command, which is equivalent to echo
                                (9) Receive parameters
                                The expect script can accept the parameters passed from the bash command line and obtain them using [lindex $argv n]. Where n starts from 0 and represents the first, second and third... Parameters respectively.

                                Example:

                                set hostname [lindex $argv 0]
                                amount to hostname=$1
                                set password [lindex $argv 1]
                                amount to password=$2
                                
                                   
                                • Expect is executed directly. You need to use the expect command to execute the script
                                  su switching users

                                  #! /usr/bin/expect
                                  #Set timeout
                                  set timeout 5
                                  
                                       
                                  • 2. Parameter incoming

                                    set username [lindex $argv 0]
                                    set password
                                    [lindex $argv 1]
                                    #Start tracking command
                                    spawn su $username
                                    #No interactive execution, capture information and match
                                    expect "password"
                                    send "Spassword\r"
                                    expect "*]#"
                                    send user "ok" .
                                    #Give control to the console
                                    interact
                                    #expect eof
                                    
                                           
                                    • 3. The embedded execution mode integrates the expect process into the Shell to facilitate execution and processing

                                      Create user and set password

                                      #! /bin/bash
                                      user=$1
                                      password=$2
                                      #Non interactive commands are placed outside expect
                                      useradd $user
                                      #Start swap free execution
                                      /usr/bin/expect <<-EOF
                                      #expect start flag
                                      spawn passwd $user
                                      #Enable - a process tracks the passwd command. expect can only capture the process information
                                      expect "new*"
                                      send "$ {password}\r" .
                                      expect "again*"
                                      send "$ {password} \r"
                                      expect eof
                                      EOF
                                      
                                               

                                Embedded:

                                #!/bin/bash
                                user=$1
                                passwd=$2
                                /usr/bin/expect <<EOF
                                spawn ssh $1 
                                expect "(yes/no)" {send "yes\r"}
                                expect "password" {send "$2\r"}
                                expect eof
                                EOF
                                
                                 

                                • 5. Interactive free disk creation

                                  #!/bin/bash
                                  disk=$1
                                  /usr/bin/expect <<-EOF
                                  spawn fdisk $disk
                                  expect "command" {send "n\r"}
                                  expect "Select" {send "\r"}
                                  expect "partition" {send "\r"}
                                  expect "start" {send "\r"}
                                  expect "Last" {send "\r"}
                                  expect "command(input m get help): " {send "w\r"}
                                  expect eof
                                  EOF
                                  partprobe
                                  mkfs.xfs $disk -f &> /dev/null
                                  if [ $? -eq 0 ]
                                  then
                                  echo -e "\033[31m Disk format complete \033[0m"
                                  mkdir $disk.1
                                  mount $disk $disk.1
                                  df -h
                                  else
                                  echo "Formatting failed, there is a problem with the script"
                                  fi
                                  
                                     

                                1. First, add a disk manually

                                2. Write a script


                                3. Install package expect by

                                4. Execute script

                                Topics: shell