34 Essential Linux Shell Scripts for Operations and Maintenance



来源:CSDN  http://985.so/xyf7






















































































































































































































































































































































































































































































































































































































































































































































As a Linux engineer, being able to write good scripts not only improves work efficiency but also gives you more time to do your own things. Recently, while surfing the internet, I collected some scripts written by experts, summarized and organized them. Feel free to bookmark this and let’s encourage each other!
(1) User Guessing Game
#!/bin/bash

# The script generates a random number within 100, prompts the user to guess the number, and based on the user's input, informs the user whether they guessed correctly, guessed too high, or guessed too low, until the user guesses correctly and the script ends.

# RANDOM is a built-in system variable that generates a random number between 0-32767
# Using the modulo operation to convert the random number to a number between 1-100
num=$[RANDOM%100+1]
echo "$num"

# Use read to prompt the user to guess the number
# Use if to compare the user's guess: -eq (equal), -ne (not equal), -gt (greater than), -ge (greater than or equal), -lt (less than), -le (less than or equal)
while :
do 
 read -p "The computer generated a random number between 1-100, your guess: " cai  
    if [ $cai -eq $num ]   
    then     
        echo "Congratulations, you guessed correctly"     
        exit  
     elif [ $cai -gt $num ]  
     then       
            echo "Oops, you guessed too high"    
       else      
            echo "Oops, you guessed too low" 
  fi
done
(2) Check How Many Remote IPs Are Connecting to This Machine
#!/bin/bash

# Check how many remote IPs are connecting to this machine (whether through ssh, web, or ftp)

# Using netstat -atn can check the status of all connections on this machine, -a shows all,
# -t only displays TCP connection information, -n displays in numeric format
# Local Address (the fourth column is the local IP and port information)
# Foreign Address (the fifth column is the remote host's IP and port information)
# Use awk to display only the 5th column data, then display the 1st column IP address information
# sort can sort by numerical size, and finally use uniq to remove excess duplicates and count the number of duplicates
netstat -atn  |  awk  '{print $5}'  | awk  '{print $1}' | sort -nr  |  uniq -c
(3) Hello World
#!/bin/bash

function example {
echo "Hello world!"
}
example
(4) Print Tomcat’s PID
#!/bin/sh

v1="Hello"
v2="world"
v3=${v1}${v2}
echo $v3

pidlist=`ps -ef|grep apache-tomcat-7.0.75|grep -v "grep"|awk '{print $2}'`
echo $pidlist
echo "Tomcat Id list :$pidlist"  // Show PID
(5) Rock, Paper, Scissors Game Script
#!/bin/bash

game=(rock scissors paper)
num=$[RANDOM%3]
computer=${game[$num]}

echo "Please choose your gesture based on the following prompts"
echo " 1. Rock"
echo " 2. Scissors"
echo " 3. Paper "

read -p "Please choose 1-3 :" person
case $person in
1)
  if [ $num -eq 0 ]
  then 
    echo "It's a tie"
    elif [ $num -eq 1 ]
    then
      echo "You win"
    else 
      echo "Computer wins"
fi;;
2)
 if [ $num -eq 0 ]
 then
    echo "Computer wins"
    elif [ $num -eq 1 ] 
    then
     echo "It's a tie"
    else 
      echo "You win"
fi;;
3)
 if [ $num -eq 0 ]
 then  
   echo "You win"
   elif [ $num -eq 1 ]
   then 
     echo "Computer wins"
   else 
      echo "It's a tie"
fi;;
*)
  echo "You must enter a number between 1-3"
esac
(6) Multiplication Table
#!/bin/bash

for i in `seq 9`
do 
 for j in `seq $i`
do 
 echo -n "$j*$i=$[i*j] "
done
echo
done
(7) Script to Install Memcached Server from Source
#!/bin/bash
# One-click deployment of memcached

# The script installs the memcached server from source
# Note: If the software download link is expired, please update the memcached download link
wget http://www.memcached.org/files/memcached-1.5.1.tar.gz
yum -y install gcc
tar -xf  memcached-1.5.1.tar.gz
cd memcached-1.5.1
./configure
make
make install
(8) Check if the Current User is a Super Administrator
#!/bin/bash

# Check if the current user is a super administrator, if so, use yum to install vsftpd, if not
# prompt that you are not an administrator (using string comparison)
if [ $USER == "root" ] 
then 
 yum -y install vsftpd
else 
 echo "You are not an administrator and do not have permission to install software"
fi
(9) If Operation Expression
#!/bin/bash -xv

if [ $1 -eq 2 ] ;then
 echo "I love Wenmin"
elif [ $1 -eq 3 ] ;then 
 echo "I love Wenxing "
elif [ $1 -eq 4 ] ;then 
 echo "My heart "
elif [ $1 -eq 5 ] ;then
 echo "My love "
fi
(10) Script to Kill Tomcat Process and Restart
#!/bin/bash

# Kill tomcat pid

pidlist=`ps -ef|grep apache-tomcat-7.0.75|grep -v "grep"|awk '{print $2}'`  # Find tomcat's PID

echo "Tomcat Id list :$pidlist"  // Show PID

kill -9 $pidlist  # Kill the process

echo "KILL $pidlist:" // Prompt process and that it has been killed

echo "Service stop success"

echo "Start tomcat"

cd /opt/apache-tomcat-7.0.75

pwd 

rm -rf work/*

cd bin

./startup.sh #;tail -f ../logs/catalina.out
(11) Print Chessboard
#!/bin/bash
# Print chessboard
# Set two variables, i and j, one represents rows, one represents columns, chessboard is 8*8
# i=1 represents preparing to print the first row of the chessboard, the first row has gray and blue alternating output, a total of 8 columns
# i=1,j=1 represents the first row's first column; i=2,j=3 represents the second row's third column
# The rule of the chessboard is if i+j is even, print blue block, if odd print gray block
# Use echo -ne to print blocks, and after printing the block, do not automatically wrap, continue to output other blocks in the same line
for i in {1..8}
do
   for j in {1..8}
do
    sum=$[i+j]
  if [  $[sum%2] -eq 0 ];then
    echo -ne "\033[46m  \033[0m"
  else
   echo -ne "\033[47m  \033[0m"
  fi
   done
   echo
done

(12) Count How Many Accounts Can Log in to the Current Linux System
#!/bin/bash

# Count how many accounts can log in to the current Linux system
# Method 1:
grep "bash$" /etc/passwd | wc -l
# Method 2:
awk -f : '/bash$/{x++}end{print x}' /etc/passwd
(13) Backup MySQL Table Data
#!/bin/sh

source /etc/profile
dbName=mysql
tableName=db
echo [`date +'%Y-%m-%d %H:%M:%S'`]' start loading data...'
mysql -uroot -proot -P3306 ${dbName} -e "LOAD DATA LOCAL INFILE '# /home/wenmin/wenxing.txt' INTO TABLE ${tableName} FIELDS TERMINATED BY ';'"
echo [`date +'%Y-%m-%d %H:%M:%S'`]' end loading data...'
exit
EOF
(14) Use Infinite Loop to Real-time Display the Data Packet Traffic Sent by eth0 Network Card
#!/bin/bash

# Use infinite loop to real-time display the data packet traffic sent by eth0 network card

while :
do 
 echo 'Local network card ens33 traffic information as follows:'
 ifconfig ens33 | grep "RX pack" | awk '{print $5}'
     ifconfig ens33 | grep "TX pack" | awk '{print $5}'
sleep 1
done
(15) Write a Script to Test Which Hosts in the 192.168.4.0/24 Network Segment Are Powered On and Which Are Off
#!/bin/bash

# Write a script to test which hosts in the 192.168.4.0/24 network segment are powered on and which are off
# Status (for version)
for i in {1..254}
do 
 # Ping once every 0.3 seconds, a total of 2 pings, and set the ping timeout to 1 millisecond
 ping -c 2 -i 0.3 -W 1 192.168.1.$i &>/dev/null
     if [ $? -eq 0 ];then
 echo "192.168.1.$i is up"
 else 
 echo "192.168.1.$i is down"
 fi
done
(16) Write a Script: Prompt User to Input Username and Password, Automatically Create Corresponding Account and Configure Password
#!/bin/bash
# Write a script: prompt user to input username and password, automatically create corresponding account and configure password. If the user
# does not input an account name, prompt that an account name must be entered and exit the script; if the user does not input a password, use the default
# 123456 as the default password.

read -p "Please enter a username: " user
# Use -z to check if a variable is empty, if empty, prompt the user must enter an account name, and exit the script, exit code is 2
# If no username is entered, after the script exits, use $? to check the return code is 2
if [ -z $user ]; then
 echo " You must enter an account name" 
 exit 2
fi 
# Use stty -echo to close the shell's echo function
# Use stty echo to open the shell's echo function
stty -echo 
read -p "Please enter a password: " pass
stty echo 
pass=${pass:-123456}
useradd "$user"
echo "$pass" | passwd --stdin "$user"
(17) Sort Three Input Integers
#!/bin/bash

# Prompt the user to input 3 integers in turn, the script sorts and outputs the 3 numbers based on their size
read -p " Please enter an integer: " num1
read -p " Please enter an integer: " num2
read -p " Please enter an integer:  " num3

# No matter who is bigger or smaller, in the end print echo "$num1,$num2,$num3"
# num1 always stores the smallest value, num2 always stores the middle value, num3 always stores the largest value
# If the input is not in this order, change the storage order of the numbers, for example: swap the values of num1 and num2
tmp=0
# If num1 is greater than num2, swap num1 and num2 to ensure the smallest value is stored in num1
if [ $num1 -gt $num2 ];then
 tmp=$num1
 num1=$num2
 num2=tmp
fi
# If num1 is greater than num3, swap num1 and num3 to ensure the smallest value is stored in num1
if [ $num1 -gt $num3 ];then
 tmp=$num1
 num1=$num3
 num3=$tmp
fi
# If num2 is greater than num3, swap num2 and num3 to ensure the smallest value is stored in num2
if [ $num2 -gt $num3 ];then
 tmp=$num2
 num2=$num3
 num3=$tmp
fi
echo "Sorted data (from smallest to largest) is: $num1,$num2,$num3"
(18) Return Greeting Based on Current Computer Time, Can Set This Script to Start at Boot
#!/bin/bash
# Return greeting based on current computer time, can set this script to start at boot

# 00-12 o'clock is morning, 12-18 o'clock is afternoon, 18-24 o'clock is evening
# Use date command to get the time, then use if to judge the time interval to determine the content of the greeting
 tm=$(date +%H)
if [ $tm -le 12 ];then
 msg="Good Morning $USER"
elif [ $tm -gt 12 -a $tm -le 18 ];then
   msg="Good Afternoon $USER"
else
   msg="Good Night $USER"
fi
echo "Current time is:$(date +"%Y‐%m‐%d %H:%M:%S")"
echo -e "\033[34m$msg\033[0m"
(19) Write ‘I love cls’ to a txt file
#!/bin/bash

cd /home/wenmin/
touch wenxing.txt
echo "I love cls" >>wenxing.txt
(20) Script to Write for Loop Judgment
#!/bin/bash

s=0;
for((i=1;i<100;i++))
do 
 s=$[$s+$i]
done 

echo $s

r=0;
a=0;
b=0;
for((x=1;x<9;x++))
do 
 a=$[$a+$x] 
echo $x
done
for((y=1;y<9;y++))
do 
 b=$[$b+$y]
echo $y

done

echo $r=$[$a+$b]
(21) Script to Write for Loop Judgment
#!/bin/bash

for i in "$*"
do 
 echo "Wenmin likes $i"
done

for j in "$@"
do 
 echo "Wenmin likes $j"
done
(22) Script to Backup All Log Files in /var/log Every Friday Using tar Command
#!/bin/bash
# Every Friday use tar command to back up all log files in /var/log
# vim  /root/logbak.sh
# Write backup script, the filename after backup contains date label to prevent the later backup from overwriting the previous backup data
# Note that the date command needs to be enclosed in backticks, backticks are above the tab key

tar -czf log-`date +%Y%m%d`.tar.gz /var/log 

# crontab -e # Write scheduled tasks, execute backup script
00 03 * * 5 /home/wenmin/datas/logbak.sh
(23) Script Writing Sum Function Operation function xx()
#!/bin/bash

function sum()
{
 s=0;
 s=$[$1+$2]
 echo $s
}
read -p "input your parameter " p1
read -p "input your parameter " p2

sum $p1 $p2

function multi()
{
 r=0;
 r=$[$1/$2]
 echo $r
}
read -p "input your parameter " x1
read -p "input your parameter " x2

multi $x1 $x2

v1=1
v2=2
let v3=$v1+$v2
echo $v3
(24) Script Writing Case — Esac Branch Structure Expression
#!/bin/bash 

case $1 in 
1) 
 echo "Wenmin "
;;
2)
 echo "Wenxing "
;; 
3)  
 echo "Wemchang "
;;
4) 
 echo "Yijun"
;;
5)
 echo "Sinian"
;;
6)  
 echo "Sikeng"
;;
7) 
 echo "Yanna"
;;
*)
 echo "Danlian"
;; 
esac
(25) Define the Page Address to be Monitored, Restart or Maintain Tomcat Status
#!/bin/sh  
# function: Automatically monitor the tomcat process, if it hangs, execute the restart operation  
# author: Huang Hong  
# DEFINE  

# Get tomcat PPID  
TomcatID=$(ps -ef |grep tomcat |grep -w 'apache-tomcat-7.0.75'|grep -v 'grep'|awk '{print $2}')  

# tomcat_startup  
StartTomcat=/opt/apache-tomcat-7.0.75/bin/startup.sh  


#TomcatCache=/usr/apache-tomcat-5.5.23/work  

# Define the page address to be monitored  
WebUrl=http://192.168.254.118:8080/

# Log output  
GetPageInfo=/dev/null  
TomcatMonitorLog=/tmp/TomcatMonitor.log  

Monitor()  
  {  
   echo "[info] Start monitoring tomcat...[$(date +'%F %H:%M:%S')]"  
   if [ $TomcatID ]
 then  
      echo "[info] Tomcat process ID is: $TomcatID."  
      # Get return status code  
      TomcatServiceCode=$(curl -s -o $GetPageInfo -m 10 --connect-timeout 10 $WebUrl -w %{http_code})  
      if [ $TomcatServiceCode -eq 200 ];then  
          echo "[info] Return code is $TomcatServiceCode, tomcat started successfully, page is normal."  
      else  
          echo "[error] Access error, status code is $TomcatServiceCode, error log has been output to $GetPageInfo"  
          echo "[error] Starting to restart tomcat"  
          kill -9 $TomcatID  # Kill original tomcat process  
          sleep 3  
          #rm -rf $TomcatCache # Clean up tomcat cache  
          $StartTomcat  
      fi  
      else  
      echo "[error] Process does not exist! Tomcat auto-restart..."  
      echo "[info] $StartTomcat, please wait......"  
      #rm -rf $TomcatCache  
      $StartTomcat  
    fi  
    echo "------------------------------"  
   }  
   Monitor>>$TomcatMonitorLog
(26) Create Linux System Accounts and Passwords through Positional Variables
#!/bin/bash

# Create Linux system accounts and passwords through positional variables

# $1 is the first parameter of the executing script, $2 is the second parameter of the executing script

useradd "$1"
echo "$2" | passwd --stdin "$1"
(27) Number of Variables Passed and Obtained and Printed
#!/bin/bash
echo "$0 $1 $2 $3"  // Pass in three parameters
echo $#    // Get the number of passed parameters
echo $@    // Print the obtained parameters
echo $*    // Print the obtained parameters
(28) Real-time Monitor Local Memory and Remaining Disk Space, Send Alarm Email to Root Administrator When Remaining Memory is Less than 500M, Remaining Space of Root Partition is Less than 1000M
#!/bin/bash

# Real-time monitor local memory and remaining disk space, send alarm email to root administrator when remaining memory is less than 500M, remaining space of root partition is less than 1000M

# Extract the remaining space of the root partition
disk_size=$(df / | awk '/
/{print $4}')

# Extract the remaining memory space
mem_size=$(free | awk '/Mem/{print $4}')
while :
do 
# Note that the size of memory and disk extracted is in Kb
if  [  $disk_size -le 512000 -a $mem_size -le 1024000  ]
then
    mail  ‐s  "Warning"  root  <<EOF
 Insufficient resources, resource insufficient
EOF
fi
done
(29) Check if Corresponding File Exists in Specified Directory
#!/bin/bash

if [ -f /home/wenmin/datas ]
then 
echo "File exists"
fi
(30) Script Defines While Loop Statement
#!/bin/bash

if [ -f /home/wenmin/datas ]
then 
echo "File exists"
fi

[root@rich datas]# cat while.sh 
#!/bin/bash

s=0
i=1
while [ $i -le 100 ]
do
        s=$[$s + $i]
        i=$[$i + 1]
done

echo $s
echo $i
(31) One-click Deployment of LNMP (RPM Package Version)
#!/bin/bash 

# One-click deployment of LNMP (RPM package version)
# Use yum to install and deploy LNMP, you need to configure the yum source in advance, otherwise this script will fail
# This script is used for centos7.2 or RHEL7.2
yum -y install httpd
yum -y install mariadb mariadb-devel mariadb-server
yum -y install php php-mysql

systemctl start httpd mariadb
systemctl enable httpd mariadb
(32) Read Console Input Parameters
#!/bin/bash
read -t 7 -p "input your name " NAME
echo $NAME

read -t 11 -p "input you age " AGE
echo $AGE

read -t 15 -p "input your friend " FRIEND
echo $FRIEND

read -t 16 -p "input your love " LOVE
echo $LOVE
(33) Script to Implement Copying
#!/bin/bash

cp $1 $2
(34) Script to Determine Whether a File Exists
#!/bin/bash

if [ -f file.txt ];then
 echo "File exists"
else 
 echo "File does not exist"
fi

Recommendations for Books

This book is a reprint of the best-selling book “Black Hat Python: Python Programming for Hackers and Penetration Testers”, which introduces how Python is used in various fields of hacking and penetration testing: from basic network scanning to packet capture, from web crawling to writing Burp plugins, from writing trojans to privilege escalation, etc.

All articles in this public account have been organized into a directory, please reply “m” in the public account to get it!

Recommended reading:

Running Native Linux on M1 Chip: Compilation Speed is 40% Faster than macOS

How the Whole Network Shows IP Attribution?

Recommended a low-code tool dedicated to management systems, developing a system in a day is not a dream!

5T Technology Resources Released! Including but not limited to: C/C++, Linux, Python, Java, PHP, Artificial Intelligence, Microcontrollers, Raspberry Pi, etc. Reply “1024” in the public account to get it for free!

Leave a Comment