linux常用的shell指令碼
一、檢查系統負載:檢查系統的負載情況,並在超過閾值時傳送警報。可使用 uptime
命令和條件語句來實現
#!/bin/bash
CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}')THRESHOLD=80THRESHOLD=80if (( $(echo "$CPU_USAGE > $THRESHOLD" | bc -l) )); then
echo"CPU usage is high: $CPU_USAGE%"
# Send alert email or trigger automated responsefi
二、備份檔案:編寫一個指令碼以定期備份指定目錄的檔案。可以使用 cp
命令和 cron
作業排程程式來完成
#!/bin/bash
backup_dir="/path/to/backup"
source_dir="/path/to/source"
timestamp=$(date +%Y%m%d%H%M%S)
backup_file="backup_$timestamp.tar.gz"
tar czf "$backup_dir/$backup_file" "$source_dir"
三、清理日誌檔案:編寫一個指令碼以清理舊的日誌檔案,保留最近的一段時間內的檔案。可以使用 find
命令和條件語句來實現
#!/bin/bash
log_dir="/path/to/logs"
days_to_keep=7
find "$log_dir" -type f -name "*.log" -mtime +$days_to_keep -delete
四、監控服務狀態:編寫一個指令碼以監控關鍵服務的執行狀態,並在服務異常時傳送警報。可以使用 systemctl
命令和條件語句來實現
#!/bin/bash
service_name="nginx"
if ! systemctl is-active --quiet "$service_name"; then
echo "服務 $service_name 未執行" | mail -s "服務狀態警報" xxx@example.com
fi
五、自動化部署:編寫一個指令碼以自動化部署應用程式或配置檔案到多臺伺服器。可以使用 rsync
命令和迴圈結構來實現
#!/bin/bash
servers=("server1" "server2" "server3")
source_dir="/path/to/source"
destination_dir="/path/to/destination"
for server in "${servers[@]}"; do
rsync -avz "$source_dir" "$server:$destination_dir"
done
六、監控磁碟空間:編寫一個指令碼以監控系統磁碟空間使用情況,並在空間不足時傳送警報。可以使用 df
命令和條件語句來實現
#!/bin/bash
threshold=90
df_output=$(df -h)
while read -r line; do
usage=$(echo "$line" | awk '{print $5}' | sed 's/%//')
if (( usage > threshold )); then
echo "磁碟空間不足: $line" | mail -s "磁碟空間警報" xx@example.com
fi
done <<< "$df_output"
七、啟動/停止服務:編寫一個指令碼以同時啟動或停止多個服務可以使用 systemctl 命令和迴圈結構來實現
#!/bin/bash
services=("service1" "service2" "service3")
action="start" # 或者 "stop"
for service in "${services[@]}"; do
systemctl "$action" "$service"
done
八、批次修改伺服器使用者密碼
# cat old_pass.txt
192.168.18.217 root 123456 22
192.168.18.218 root 123456 22
內容格式:IP User Password Port
SSH遠端修改密碼指令碼:新密碼隨機生成
https://www.linuxprobe.com/books
#!/bin/bash
OLD_INFO=old_pass.txt
NEW_INFO=new_pass.txt
for IP in $(awk '/^[^#]/{print $1}' $OLD_INFO); do
USER=$(awk -v I=$IP 'I==$1{print $2}' $OLD_INFO)
PASS=$(awk -v I=$IP 'I==$1{print $3}' $OLD_INFO)
PORT=$(awk -v I=$IP 'I==$1{print $4}' $OLD_INFO)
NEW_PASS=$(mkpasswd -l 8) # 隨機密碼
echo "$IP $USER $NEW_PASS $PORT" >> $NEW_INFO
expect -c "
spawn ssh -p$PORT $USER@$IP
set timeout 2
expect {
\"(yes/no)\" {send \"yes\r\";exp_continue}
\"password:\" {send \"$PASS\r\";exp_continue}
\"$USER@*\" {send \"echo \'$NEW_PASS\' |passwd --stdin $USER\r exit\r\";exp_continue}
}"
done
生成新密碼檔案:
# cat new_pass.txt
192.168.18.217 root n8wX3mU% 22
192.168.18.218 root c87;ZnnL 22
Linux主機SSH連線資訊:舊密碼
九、資料處理指令碼
#!/bin/bash
DATA_FILE="data.csv"
OUTPUT_FILE="processed_data.csv"
# Remove header and extract specific columns
tail -n +2 "$DATA_FILE" | cut -d ',' -f 1,3 > "$OUTPUT_FILE"
echo "Data processing completed. Processed data saved to $OUTPUT_FILE"
十、自動化測試指令碼
#!/bin/bash
TEST_URL="http://example.com"
EXPECTED_RESPONSE="200 OK"
TEST_RESULT=$(curl -s -o /dev/null -w "%{http_code}" $TEST_URL)
if [ "$TEST_RESULT" = "$EXPECTED_RESPONSE" ]; then
echo "Test passed: HTTP status code is 200 OK"
else
echo "Test failed: HTTP status code is not 200 OK"
fi
十一、日常維護指令碼
#!/bin/bash
# Check disk space usage
df -h
# Check system load
uptime
# Check running processes
ps aux
# Check system logs for errors
tail /var/log/syslog | grep "error"
# Check for available software updates
apt update
apt list --upgradable
十二、效能最佳化指令碼
#!/bin/bash
# Check CPU usage
top -b -n 1 | grep "Cpu(s)"
# Check memory usage
free -h
# Check disk I/O
iostat
# Check network usage
iftop
# Check for high load processes
ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cpu