- 定时备份文件
#!/bin/bash
backup_dir="/data1/backup"
src_dir="/data1/app"
date_time=$(date +%Y%m%d_%H%M%S)
tar -czvf ${backup_dir}/${date_time}.tar.gz ${src_dir}
- 批量更改文件后缀名
#!/bin/bash
for file in *.jpg
do
mv "$file" "${file%jpg}png"
done
- 根据文件大小清理指定目录
#!/bin/bash
dir="/data/log"
max_size="50M"
find ${dir} -type f -size +${max_size} -delete
- 自动解压文件并删除原文件
#!/bin/bash
for file in *.zip
do
unzip ${file} && rm ${file}
done
- 监控服务器内存使用情况
#!/bin/bash
total_mem=$(free -m | awk 'NR==2{print $2}')
used_mem=$(free -m | awk 'NR==2{print $3}')
percent=$(bc -l <<< "scale=2;${used_mem}/${total_mem}*100")
if (( $(echo "${percent} > 80" | bc -l) )); then
echo "Memory usage exceeds 80%!"
# Send notification email or alert
fi
- 传参数启动java项目
#! /bin/bash
#jar包的文件路径
APP_NAME="$2"
PORT=9086
help(){
echo "====================================="
echo "项目地址: ${APP_NAME}"
echo "你可以使用如下参数进行操作"
echo "-status -查看当前项目运行状态"
echo "-start -启动当前项目"
echo "-stop -停止当前项目"
echo "-restart -重启当前项目"
echo "====================================="
}
#查找jar包进程,排除grep,进程信息的第二个字段:即进程号
pid=`netstat -apn |grep $PORT |awk '{print $7}' |cut -d/ -f 1`
status(){
if [ -z "$pid" ]
then
echo "项目已停止运行"
else
echo "项目正在运行..."
echo "进程号:$pid"
echo "项目名称:$APP_NAME"
fi
}
start(){
if [ -z "$pid" ]
then
echo "正在启动..."
nohup java -Dspring.profiles.active=prod -jar $APP_NAME >/dev/null 2>nohup &
tail -f -n 200 nohup.out
else
echo "项目正在运行中或端口被占用"
echo "进程号:$pid"
fi
}
stop(){
if [ -z "$pid" ]
then
echo "项目已经停止"
else
kill -9 $pid
echo "完成停止项目"
fi
}
restart(){
if [ -z "$pid" ]
then
echo "项目未启动"
else
kill -9 $pid
fi
sleep 5
start
echo "完成项目重启"
}
case "$1" in
"-status")
status
;;
"-start")
start
;;
"-stop")
stop
;;
"-restart")
restart
;;
"-help")
help
;;
*)
help
;;
esac
- 自动备份MySQL数据库
#!/bin/bash
db_host="127.0.0.1"
db_port="3306"
db_user="root"
db_pass="password"
db_name="mydb"
backup_dir="/data/backup"
date_time=$(date +%Y%m%d_%H%M%S)
mysqldump -h${db_host} -P${db_port} -u${db_user} -p${db_pass} ${db_name} | gzip > ${backup_dir}/${db_name}-${date_time}.sql.gz
- 扫描服务器端口并发送报告邮件
#!/bin/bash
host_ip="127.0.0.1"
report_file="/tmp/port_scan_report.txt"
for port in {1..65535}
do
timeout 1 bash -c "echo >/dev/tcp/${host_ip}/${port}" 2>/dev/null && echo "${host_ip}:${port} is open" >> ${report_file}
done
# Send report email
mail -s "Port scan report" admin@example.com < ${report_file}
- 定时同步文件到远程服务器
#!/bin/bash
local_file="/data/app/myfile"
remote_host="192.168.1.100"
remote_port="22"
remote_user="root"
remote_file="/data/files/myfile"
ssh_key="/root/.ssh/id_rsa"
md5sum_local=$(md5sum ${local_file} | awk '{print $1}')
md5sum_remote=$(ssh -i ${ssh_key} -p ${remote_port} ${remote_user}@${remote_host} "md5sum ${remote_file} 2>/dev/null" | awk '{print $1}')
if [ "${md5sum_local}" != "${md5sum_remote}" ]; then
scp -i ${ssh_key} -P ${remote_port} ${local_file} ${remote_user}@${remote_host}:${remote_file}
fi