Loop nesting and extension of shell (function)

Posted by astronaut on Thu, 17 Feb 2022 17:00:20 +0100

1, Random number


1. Practical cases:

Write a script to generate a phoneNum Txt file, randomly generate 100 mobile phone numbers starting with 139, one line for each

analysis

  • Generate 100 phone numbers, and the script needs to cycle 100 times
  • 139 + 8 bits, the last 8 bits are generated randomly, which can generate every digit randomly, $[RANDOM%10]
  • Save the randomly generated numbers into variables, and then add 139 to save them into the document

2. Practical cases:

Draw five lucky viewers from the above 100 mobile phone numbers to show the five lucky viewers. However, only the first three numbers and the last four numbers are displayed, and the middle ones are replaced by *

Idea:

  • RANDOM is generated by determining the row of the lucky audience
  • Extract the phone number head and tail
  • Display the first three and last four digits to the screen, and finally output the phone number to the screen


①. Optimization:

When users are drawn, they will be deleted from the lottery list to ensure that they will not be drawn twice


2, Nested loop

A loop contains another complete loop structure, which is called loop nesting. During each execution of the external loop, the internal loop will be triggered until the internal loop is completed, and then the next external loop will be executed. for loop, while loop and until loop can be nested with each other

1. Case 1:


2. Case 2:


3. Case 3 (print 99 multiplication table):


3, shift extension

Move the position parameter to the left by 1 bit by default. You can use shift 2


4, expect program interaction

expect automatic response tcl language

Log in to another host remotely and do nothing

Two execution modes (it is not a shell script)

Log in to another host and create a file


1. Variable definition:

2. Use position parameters:

5, expect combined with shell script

shell script and expect are used together to create a user on multiple servers


Idea:

  • loop
  • Log in to remote host – > SSH – > from ip Txt file to obtain the ip and password and assign them to two variables respectively
  • Using expect program to solve interaction problems

6, Comprehensive case

Write a script to push the public key of yunwei users on the springboard to all hosts that can ping in the LAN

Case study:

  • Turn off firewall and selinux
  • Cycle to determine which ip addresses in the LAN can be ping ed
  • Get the ip of the host and the password saving variable ip pass in the password file
  • Determine whether the public key exists
  • SSH copy ID pushes the public key of yunwei user on the springboard machine to the remote host – > expect to solve the interaction problem
  • Save the ip address of the ping ed host to a separate file

Code split:

  • Obtain the ip address and determine whether it can be ping ed
  • Host password file IP txt
  • Loop to judge whether the host can ping
    • cat ip.txt|while read ip pass
      • do
        • ping -c1 $ip &>/dev/null
        • if [ $? -eq 0 ];then
        • Determine whether the public key exists
        • Push public key
        • fi
      • done
        • Judge whether the public key of yunwei user exists
        • [ ! -f /home/yunwei/.ssh/id_rsa ] && ssh -P " " -f ./id_rsa
  • Non interactive push public key
    • /usr/bin/expect <<-END &>/dev/null
    • spawn ssh-copy-id root@$ip
    • expect {
      • "yes/no" { send "yes\r";exp_continue }
      • "password" { send "$pass\r" }
    • }
    • expect eof
    • END

1. Realize:



7, Case

Write a script to count the number of different connection states of the web server

8, case statement

The case statement is a multiple selection statement. You can use a case statement to match a value with a pattern. If the match is successful, execute the matching command

1. Case 1:

When three different parameters start, stop and reload are passed into the program, execute the corresponding commands respectively

2. Case 2:

The script prompts the user to enter the name of the service to be managed, and then prompts the user what to do with the service, such as startup, shutdown, restart, etc

3. Application cases:

#!/bin/bash
#echo -e "h 	 Show command help \ nf 	 Show disk partitions \ nd 	 Show disk mount \ nm 	 View memory usage \ nu 	 View system load \ nq 	 Exit program“
cat <<-END
	h	Display command help
	f	Show disk partitions
	d	Display disk mount
	m	View memory usage
	u	View system load
	q	Exit program
	END
read -p "Please select operation number:" num
case $num in
     h)
     cat <<-END
        h       Display command help
        f       Show disk partitions
        d       Display disk mount
        m       View memory usage
        u       View system load
        q       Exit program
	END
     ;;
     f)
     df -h
     ;;
     d)
     lsblk
     ;;
     m)
     free -h
     ;;
     u)
     uptime
     ;;
     q)
     exit
     ;;
esac

But this execution is over once

①. Optimization:

1. Use functions to reduce the amount of code

#!/bin/bash
#echo -e "h 	 Show command help \ nf 	 Show disk partitions \ nd 	 Show disk mount \ nm 	 View memory usage \ nu 	 View system load \ nq 	 Exit program“
menu(){    #This is the definition function
cat <<-END
	h	Display command help
	f	Show disk partitions
	d	Display disk mount
	m	View memory usage
	u	Load system view
	q	Exit program
	END
}
menu  #Call function
read -p "Please select operation number:" num
case $num in
     h)
     menu  #Call function
     ;; 
     f)
     df -h
     ;;
     d)
     lsblk
     ;;
     m)
     free -h
     ;;
     u)
     uptime
     ;;
     q)
     exit
     ;;
esac

Let the program cycle until you press q to exit

#!/bin/bash
#echo -e "h 	 Show command help \ nf 	 Show disk partitions \ nd 	 Show disk mount \ nm 	 View memory usage \ nu 	 View system load \ nq 	 Exit program“
menu(){
cat <<-END
	h	Display command help
	f	Show disk partitions
	d	Display disk mount
	m	View memory usage
	u	View system load
	q	Exit program
	END
}
menu
while true  #Set an endless loop, and do not exit until you exit
do
read -p "Please select operation number:" num
case $num in
     h)
     menu
     ;;
     f)
     df -h
     ;;
     d)
     lsblk
     ;;
     m)
     free -h
     ;;
     u)
     uptime
     ;;
     q)
     exit
     ;;
esac
done

9, Function

shell allows a set of commands or statements to form a piece of available code, which is called shell function. Give this code a name as the function name, and you can call the function of this code directly later

1. Definition of function:

2. Function call:

  • If it is another function written separately, you need to save the source file, and then directly execute the function name
  • In addition, if the written function file needs to be used in the script, click source in the script, and then write the function name directly to call
  • If you want other users to use it, you need to write all the functions into the / etc/bashrc file

10, return description in function

  • return can end a function, similar to the loop control statement break (end the current loop and execute the code behind the loop body)
  • return returns the exit status of the last command in the function by default. You can also give a parameter value, which ranges from 0 to 256
  • If there is no return command, the function returns the exit value of the last shell

1. Application case:

Requirements: write a script to let the user input basic information (name, gender, age). If not, always prompt for input. Finally, output the corresponding content according to the user's information

Idea:

  • Loop until the input string is not empty (this function can be defined as a function for easy calling)
  • Make matching judgment case statement according to user input information
#!/bin/bash
input_fun(){
   input_var=""
   output_var=$1
   while [ -z $input_var ]
     do
       read -p "$output_var" input_var
     done
     echo $input_var
}
name=$(input_fun Please enter your name:)
sex=$(input_fun Please enter your gender:)
age=$(input_fun Please enter your age:)
echo $name
echo $sex
echo $age
case $sex in
  male)
  if [ $age -gt 18 -a $age -le 35 ];then
      echo "Middle aged uncle, are you greasy? Come on, come on!"
  elif [ $age -gt 35 ];then
    echo "Soak Chinese wolfberry in a thermos cup!"
  else
    echo "young and promising!"
  fi
  ;;
  female)
  if [ $age -gt 18 -a -le 35 ];then
    echo "Women must pay attention to maintenance at a certain age!"
  elif [ $age -gt 35 ];then
    echo "When people are middle-aged, pay attention to controlling their temper!"
  else 
    echo "Young, energetic and beautiful girl!"
  fi
  ;;
esac

2. Comprehensive cases:

Mission background:
Although the existing springboard machine realizes a unified entrance to access the production server, yunwei has too much user authority and can operate all directory files on the springboard machine, which has the hidden danger of data being deleted by mistake. Therefore, we hope to make some security strategies to ensure the normal use of the springboard machine

Specific requirements:

  • Only yunwei users are allowed to remotely connect to the application server in the background through the springboard machine to do some maintenance operations
  • When the company's operation and maintenance personnel remotely connect the springboard machine through yunwei users, the following menu will pop up for selection
  • When the user selects the corresponding host, he can log in directly and successfully without secret
  • If the user does not enter, he will always be prompted to enter until the user chooses to exit

analysis:

  • Print menu – > define function echo cat
  • Let the user select the machine to be operated ----- > Case... esac
  • Configure password free login
  • Each menu provides selection function - > Case... esac what users choose to do
  • Loop allows the user to enter a selection
  • Each function is written as a function - > not required
  • Script location -------- > Yunwei user's home directory
    In order to keep it in the springboard interface, write the bash script name and exit under bashrc in the home directory

#!/bin/bash
#jump-server
#Define function
#Define the function of menu printing
trap '' 1 2 3 19
menu(){
  cat<<-EOF
  Welcome jump-server,Please select the host you want to operate:
  1.DB-Master
  2.DB-Slave
  3.web1
  4.web2
  h.help
  q.exit
	EOF
}
menu1(){
  cat<<-EOF
  Welcome to web-server,Please select the content you want to operate:
  1.Clean up log
  2.start-up Apache
  3.restart Apache
  h.help 
	EOF
}
menu
while true
do
#The user selects the corresponding host operation
read -p "Please select the host you want to operate:" host
case $host in
       1)
       ssh root@192.168.74.15
       ;;
       2)
       ;;
       3)
       menu1
       read -p "Please enter the content you want to operate:" actions
       case $actions in
                 1)
                 ssh root@192.168.74.15
                 echo "Log cleaning in progress!"
                 ;;
                 2)
                 ssh root@192.168.74.15
                 systemctl start httpd
                 ;;
                 3)
                 ssh root@192.168.74.15
                 systemctl restart httpd
                 ;;
                 h)
                 menu1
                 ;;
                 *)
                     echo "Please select the host you want to operate:"
                 ;;
       esac
       menu
       ;;
       4)
       ;;
       h)
       menu
       ;;
       q)
       exit
       ;;
esac
done

Topics: shell