Table of contents
1. Shell script to configure the environment
Second, the system resource script
4. Empowerment and verification
4. View the real-time traffic script of the network card
6. Statistically visit the top ten IPs
1. First simulate the creation of IP and write scripts
Second, verify the ip generation result
7. Disk usage detection script
1. First lsblk to check the disk situation
8. Back up the current date file
Because I am new to shell scripts, I can only keep counting shell scripts that are different from mobile phones. The level is limited. I hope it can help everyone. If there are mistakes, please point them out in time, and we will make progress together, (#^.^#).
1. Shell script to configure the environment
systemctl stop firewalld
systemctl disable firewalld
systemctl stop NetworkManager
systemctl disable NetworkManager
setenforce 0
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
cat << e > /etc/sysconfig/network-scripts/ifcfg-ens33
TYPE=Ethernet
BOOTPROTO=static
NAME=ens33
DEVICE=ens33
ONBOOT=yes
IPADDR=$1
PREFIX=24
GATEWAY=192.168.115.2
DNS1=192.168.115.2
e
systemctl restart network
Put this script into the terminal, and then enter the IP you want to set to successfully configure the environment and set the ip
Results view
Second, the system resource script
1. Requirements
1. Write a script to monitor system resources such as CPU usage, memory usage, disk space, etc.
2. Display the usage of system resources in real time, and provide alarm function according to the preset threshold.
3. The script should be able to run in the background and automatically update the resource status at regular intervals.
4. Provide a simple user interface (command line or graphical interface), which is convenient for users to view the current system resources.
2. Script content
#! /bin/bash
#lsq
#Monitoring script
while true
do
times=10
#Disk
disk=$(df -Th | awk '{ print $6 }' | awk 'NR==6' |cut -d "%" -f 1 )
#Memory
mem=$(free -m | grep "Mem" | awk '{ printf "%.0f", $3/$2 * 100 }') #cpu cpu=$(top -n 1 | grep "Cpu
(
s )" | awk '{ printf "%.0f",
echo "Memory usage has reached $mem %, please note" && exit 0
fi
if [ $cpu -ge $cpu1 ];then
echo "CPU usage has reached $cpu %, please note" && exit 0
fi
if [ $disk - ge $disk1 ];then
echo "The disk usage has reached $disk, please pay attention" && exit 0
fi
sleep $times
done
3. Script analysis
This is a monitoring script to monitor the disk, memory and CPU usage of the system. The following is an analysis of each part of the script:
-
#!/bin/bash
: Specifies that the script uses the Bash interpreter. -
#mpy
: Comment, used to explain the purpose of the script. -
while true
: An infinite loop, indicating that the script will continue to execute. -
dotimes=10
: Set the value of a variable dotimes to 10. -
disk=$(df -Th | awk '{ print $6 }' | awk 'NR==6' |cut -d "%" -f 1)
: Use the df command to obtain disk information, and use the awk and cut commands to extract the numerical part of the disk usage. -
mem=$(free -m | grep "Mem" | awk '{ printf "%.0f", $3/$2 * 100 }')
: Use the free command to obtain memory information, and then use the awk command to calculate the percentage of memory usage. -
cpu=$(top -n 1 | grep "Cpu(s)" | awk '{ printf "%.0f", $2+$4 }')
: Use the top command to get CPU information, and use the awk command to calculate the percentage of CPU usage. -
echo "******************"
: Print separator lines. -
echo "CPU使用率$cpu %"
: Print CPU usage. -
echo "内存使用率$mem %"
: Print memory usage. -
echo "磁盘使用率$disk %"
: Print disk usage. -
echo "******************"
: Print separator lines. -
disk1=80
: Set the value of a variable disk1 to 80, indicating the threshold of disk usage. -
mem1=80
: Set the value of a variable mem1 to 80, indicating the threshold of memory usage. -
cpu1=80
: Set the value of a variable cpu1 to 80, indicating the threshold of CPU usage. -
if [ "$mem" -ge "$mem1" ]; then
: If the memory usage is greater than or equal to the threshold mem1, execute the following command. -
echo "内存使用已到$mem %,请注意" && exit 0
: Print a warning message that the memory usage reaches the threshold and exit the script. -
if [ $cpu -ge $cpu1 ]; then
: If the CPU usage is greater than or equal to the threshold cpu1, execute the following command. -
echo "CPU使用已到$cpu %,请注意" && exit 0
: Print the warning message that the CPU usage reaches the threshold and exit the script. -
if [ $disk -ge $disk1 ]; then
: If the disk usage is greater than or equal to the threshold disk1, execute the following command. -
echo "磁盘使用已到$disk ,请注意" && exit 0
: Print a warning message that the disk usage reaches the threshold and exit the script. -
sleep $times
: Pause script execution for a period of time specified by the variable times. -
done
: End the while loop.
4. Empowerment and verification
3. Script to view the total size of the current memory, the actual size used, the remaining size, and the percentage of usage
1. The first method
#!/bin/bash
Mem_all=$(free -m | awk '/Mem/ {print $2}')
Mem_used=$(free -m | awk '/Mem/ {print $3}')
Mem_free=$(free -m | awk '/Mem/ {print $4}')
Mem_usage=$(free -m | awk '/Mem/ {printf "%.0f", $3/$2 * 100}')
echo "Total current memory: $Mem_all MB"
echo "Current memory used: $Mem_used MB"
echo "Current remaining: $Mem_free MB"
echo "Current physical memory usage: $Mem_usage%"
Two, verification
3. The second method
#!/bin/bash
# Get memory information
mem_info=$(free -m | awk 'NR==2{print}')
# Get total, used and remaining memory in megabytes
total=$(echo $mem_info | awk '{print $2}')
used=$(echo $mem_info | awk '{print $3} ')
free=$(echo $mem_info | awk '{print $4}')
# Calculate memory usage
usage_percent=$(echo "scale=2; $used / $total * 100" | bc)
# Print information
echo "Total physical memory: ${total}MB"
echo "Used memory: ${used}MB"
echo "Remaining memory: ${free}MB"
echo "Memory usage: ${usage_percent}% "
4. Verification
4. View the real-time traffic script of the network card
1. Edit script
#!/bin/bash
NIC=ens33
echo -e " In ------ Out"
while true; do
OLD_IN=$(awk '$0~"'$NIC'"{print $2}' /proc/net/dev)
OLD_OUT=$(awk '$0~"'$NIC'"{print $10}' /proc/net/dev)
sleep 1
NEW_IN=$(awk '$0~"'$NIC'"{print $2}' /proc/net/dev)
NEW_OUT=$(awk '$0~"'$NIC'"{print $10}' /proc/net/dev)
IN=$(printf "%.1f%s" "$((($NEW_IN-$OLD_IN)/1024))" "KB/s")
OUT=$(printf "%.1f%s" "$((($NEW_OUT-$OLD_OUT)/1024))" "KB/s")
echo "$IN $OUT"
sleep 1
done
2. Verification results
5. Change the suffix of all files with the suffix ".sh" in the current directory (including subdirectories) to ".shell", and then delete the second line of each file.
First look at the suffix files in the directory
1. Write a script
#!/bin/bash
ALL_SH_FILE=$(find . -type f -name "*.sh")
for file in ${ALL_SH_FILE[*]}
do
filename=$(echo $file | awk -F'.sh' '{print $1}')
new_filename="${filename}.shell"
mv "$file" "$new_filename"
sed -i '2d' "$new_filename"
done
Two, verification
6. Statistically visit the top ten IPs
1. First simulate the creation of IP and write scripts
vim /makeiplog.sh
#!/bin/bash
for i in {1..30};do
host=$[$RANDOM % 10]
host1=$[$RANDOM % 10]
echo "192.168.$host1.$host" >> /root/ip.log
done
Empower and activate
Second, verify the ip generation result
Enter vim ip.log to view
input the command
awk '{a[$1]++}END{print "UV:",length(a);for(v in a)print v,a[v]}' ip.log |sort -k2 -nr |head -10
Show results
awk '{a[$1]++}END{print "UV:",length(a);for(v in a)print v,a[v]}' ip.log |sort -k2
display in ascending order
7. Disk usage detection script
1. First lsblk to check the disk situation
echo fdisk.sh create
Second, enter the script
#!/bin/bash
# Intercept IP
IP=`ifconfig eth0 |awk -F " " 'NR==2{print $2}'`
# Define the usage rate and convert it to a number
SPACE=`df -Ph |awk '{ print int($5)}'`
for i in $SPACE
do
if [ $i -ge 80 ]
then
echo "The disk usage of $IP has exceeded 80%, please deal with it in time"
fi
done
Authorize and verify the result
If you change the script content to 90, it will prompt more than 90% during verification
./fdisk.sh verify
8. Back up the current date file
1. Write a script
#!/bin/bash
#一月前
historyTime=$(date "+%Y-%m-%d %H" -d '1 month ago')
echo ${historyTime}
historyTimeStamp=$(date -d "$historyTime" +%s)
echo ${historyTimeStamp}
#一周前
date_this_month=`date +%Y%m01`
#一天前
date_today=`date -d '1 day ago' +%Y%m%d`
It's a Bash script, and here's an explanation of each part:
-
historyTime=$(date "+%Y-%m-%d %H" -d '1 month ago')
: Get the date and time one month ago and store it in a variablehistoryTime
.date
The options of the command-d
are used to specify the date,"+%Y-%m-%d %H"
indicating that the output format is year-month-day-hour. -
echo ${historyTime}
: PrinthistoryTime
the value of the variable, which is the date and time one month ago. -
historyTimeStamp=$(date -d "$historyTime" +%s)
:historyTime
Convert the variable into a timestamp format and store it in the variablehistoryTimeStamp
.date
Options to the command-d
are used to specify a date,+%s
which represents the output timestamp. -
echo ${historyTimeStamp}
: PrinthistoryTimeStamp
the value of the variable, which is the timestamp one month ago. -
date_this_month=
date +%Y%m01``: Get the year and month of the current month, and add "01" at the end to indicate the first day of the current month. The result is stored in a variabledate_this_month
. -
date_today=
date -d '1 day ago' +%Y%m%d``: Get yesterday's date and store it in a variable in the format of year, month, anddate_today
day .
The purpose of this script is to get the date and time before January and convert it into a timestamp format. Then, get the date of the first day of the month and yesterday's date.
2. Script result verification
root@localhost ~]# ./jiaoben.sh
2023-07-29 21
1690635600