ubuntu 20.04 编写上电自启动shell脚本
1、 编写脚本是查看CPU核0,CPU0的负载情况check_cpu.sh,对于自启动代码一般路径都需要写成绝对路径;
#!/bin/bash sleep 80 LIMIT=50 while true; do CPU0_usage=$(top -1 -bn 1 | grep -P "^(%Cpu0)" | sed 's/%Cpu0.*,\s*\(\S*\) id.*/\1/') if [ -n ${CPU0_usage} ]; then if (( $(echo "${CPU0_usage} < ${LIMIT}" | bc -l) )); then timestamp=$(date +"%Y%m%d%H%M%S") process_file="/opt/other/process_info_${timestamp}.txt" system_file="/opt/other/system_info_${timestamp}.txt" top -1 bn1 | grep Cpu0 >> "$process_file" ps -eLo psr,tid,class,rtprio,ni,pri,pid,pcpu,stat,wchan:14,comm,args --sort -pcpu | head -n 1 >> "$process_file" ps -eLo psr,tid,class,rtprio,ni,pri,pid,pcpu,stat,wchan:14,comm,args --sort -pcpu | awk '$1 ~ /^0+$/' >> "$process_file" fi fi sleep 3 done
2、将check_cpu.sh 拷贝到ubuntu的/home/文件夹下,chmod 777 check_cpu.sh,然后执行如下配置
cd /etc/systemd/system touch check_cpu.service
2.1、编写check_cpu.service vim check_cpu.service
[Unit] Description=check_cpu_load After=syslog.target [Service] ExecStart=/bin/bash /home/check_cpu.sh SuccessExitStatus=143 RemainAfterExit=yes [Install] WantedBy=multi-user.target
3、设置自启动systemctl enable check_cpu.service 开启 (开启了,但还没生效,要重启计算机)
下面的命令是常用的查看
systemctl enable check_cpu.service #开启 (开启了,但还没生效,要重启计算机) systemctl restart check_cpu.service #重启 systemctl stop check_cpu.service #停止 systemctl status check_cpu.service #查看开启状态