当前位置: 首页 > news >正文

shell脚本02

if 条件语句

if 条件语句实践

检测sshd服务是否运行,如果未运行则启动sshd服务。如果运行,输出 “Running”。

[root@webapp ~ 17:03:10]# vim ./ssh_ctl_if_1.sh 
#!/bin/bash
systemctl is-active sshd &>/dev/null
return_count=$?if (( return_count!=0 ));thenecho "Sshd is not running."echo -n "Starting sshd ... "systemctl start sshd && echo Success || echo Fail
elseecho "Sshd is running."#echo -n "Stopping sshd ... "#systemctl stop sshd && echo Success || echo Fail
fi

通过传参控制sshd服务。

[root@webapp ~ 17:03:19]# vim ssh_ctl_if_3.sh 
#!/bin/bashif [ "$1" = "start" ];thensystemctl $1 sshd
elif [ "$1" = "stop" ];thensystemctl $1 sshd
elif [ "$1" = "status" ];thensystemctl $1 sshd
elseecho "Usage: $0 start|stop|status"
fi

实践

需求:每1分钟检查一次系统可用内存,如果空闲内存低于100M时给root用户发邮件。
1. 每1分钟运行一次脚本 cron定时任务完成
2. 检查内存 free -m | awk '/Mem/ {print $4}'
3. 发邮件 mailx,具体命令示例 mail -s "test" root < /etc/hosts
[root@webapp ~ 17:06:59]# crontab -e
* * * * * /root/bin/check_memory.sh[root@webapp bin 17:08:52]# vim check_memory.sh 
#!/bin/bash
memory_available_size=$(free -m | awk '/Mem/ {print $NF}')
memory_min_size=10000
if ((memory_free_size<memory_min_size));thenecho "Current available memory size is ${memory_available_size}" | \mail -s "memory size is lower" root
fi

case条件语句

给输出的字符串加颜色

[root@webapp bin 17:11:52]# vim case2.sh
#!/bin/bash
case $1 inPASS)echo -e '\033[1;32mPASS\033[0;39m';;FAIL)echo -e '\033[1;31mFAIL\033[0;39m';;DONE)echo -e '\033[1;35mDONE\033[0;39m';;*)echo "Usage: $0 PASS|FAIL|DONE";;
esac

在这里插入图片描述

管理用户

通过传参的方式往 /etc/users 里添加用户,具体要求如下。

  1. 命令用法为:

    Usage: user-mgr [ [-add|-a ] | [ -d|-del ] | [ -s|-search ] ] username

  2. 传参要求为:

    • 参数为-add|-a时,表示添加后面接的用户名。如果有同名的用户, 则不能添加。
    • 参数为-del|-d时,表示删除后面接的用户名。如果用户不存在,提示用户不存在。
    • 参数为-search|-s时,表示查找后面接的用户名。 如果用户不存在,提示用户不存在。
    • 没有用户时应给出明确提示。
[root@webapp bin 14:49:57]# vim user-mgr.sh
#!/bin/bash# run as root
[ $UID -ne 0 ] && echo 'Please run as root' && exit 1# create users file
users_info_file=/etc/users
[ -f ${users_info_file} ] || touch ${users_info_file}# provides two args
if [ $# -ne 2 ];thenecho "Usage: user-mgr [ [-add|-a ]ca | [ -d|-del ] | [ -s|-search ] ] username"exit 2
fi# get arg value
action=$1
username=$2
# manager user
case $action in-s|-search)if grep -q "username: $username" ${users_info_file};thenecho "$username is exist."elseecho "$username is not exist."fi;;-a|-add)if grep -q "username: $username" ${users_info_file};thenecho "$username is exist."elsechattr -i ${users_info_file} echo "username: $username" >> ${users_info_file}echo "$username has been added."chattr +i ${users_info_file} fi;;-d|-del)if grep -q "username: $username" ${users_info_file};thenchattr -i ${users_info_file} sed -i "/username: $username/d" ${users_info_file}chattr +i ${users_info_file} echo "$username has been deleted."elseecho "$username is not exist."fi;;*)echo "Usage: user-mgr [ [-add|-a ] | [ -d|-del ] | [ -s|-search ] ] username" ;;
esac

验证

[root@webapp bin 14:50:28]# cat /etc/users[root@webapp bin 14:51:55]# bash user-mgr.sh -s zlx
zlx is not exist.[root@webapp bin 14:52:21]# bash user-mgr.sh -s zlxx
zlxx is exist.
[root@webapp bin 14:52:46]# cat /etc/users 
username: zlxx

while循环语句

while 循环语句会对紧跟在while命令后的条件表达式进行判断:

  • 如果该条件表达式成立,则执行while 循环体里的命令或语句(即语法中do和done之间的指令),每一次执行到done时就会重新判断while条件表达式是否成立,直到条件表达式不成立时才会跳出while 循环体。
  • 如果一开始条件表达式就不成立,那么程序就不会进入循环体(即语法中do和done之间的部分)中执行命令了。

示例:每次工作赚100w,赚到1000w就停止工作

[root@webapp bin 14:52:55]# vim makemoney.sh
#!/bin/bashmoney=0
target=10000000
while [ $money -lt $target ] 
doecho -n "I'm working hard ... total:  "money=$[ money+1000000 ]echo $moneysleep 0.5
done
[root@webapp bin 15:33:19]# bash makemoney.sh
I'm working hard ... total:  1000000
I'm working hard ... total:  2000000
I'm working hard ... total:  3000000
I'm working hard ... total:  4000000
I'm working hard ... total:  5000000
I'm working hard ... total:  6000000
I'm working hard ... total:  7000000
I'm working hard ... total:  8000000
I'm working hard ... total:  9000000
I'm working hard ... total:  10000000

示例2: 后台监视sshd服务,一旦发现sshd服务未运行,就start sshd。每隔3秒检测一次。不允许使用计划任务(cron)。

[root@webapp bin 15:41:34]# vim jianshi.sh#!/bin/bash
while true
dosystemctl is-active sshd &>/dev/nullreturn_count=$?if (( return_count!=0 ));thensystemctl start sshd elsesleep 3fi
done

验证:

#关闭sshd服务
[root@webapp ~ 15:40:43]# systemctl stop sshd
#检查sshd服务状态
[root@webapp ~ 15:42:05]# systemctl status sshd
● sshd.service - OpenSSH server daemonLoaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)Active: inactive (dead) since 五 2025-10-10 15:41:47 CST; 27s agoDocs: man:sshd(8)man:sshd_config(5)Process: 20298 ExecStart=/usr/sbin/sshd -D $OPTIONS (code=exited, status=0/SUCCESS)Main PID: 20298 (code=exited, status=0/SUCCESS)#启动脚本
[root@webapp bin 15:40:14]# bash jianshi.sh#再次检查sshd服务状态
[root@webapp ~ 15:42:15]# systemctl status sshd
● sshd.service - OpenSSH server daemonLoaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)Active: active (running) since 五 2025-10-10 15:42:24 CST; 5s agoDocs: man:sshd(8)man:sshd_config(5)Main PID: 22551 (sshd)Tasks: 1CGroup: /system.slice/sshd.service└─22551 /usr/sbin/sshd -D#用指令关闭sshd服务后再检查sshd服务状态,发现sshd关闭后很快就会被再次启动
[root@webapp ~ 15:41:25]# systemctl stop sshd
[root@webapp ~ 15:42:15]# systemctl status sshd
● sshd.service - OpenSSH server daemonLoaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)Active: active (running) since 五 2025-10-10 15:42:24 CST; 5s agoDocs: man:sshd(8)man:sshd_config(5)Main PID: 22551 (sshd)Tasks: 1CGroup: /system.slice/sshd.service└─22551 /usr/sbin/sshd -D

.service; enabled; vendor preset: enabled)
Active: active (running) since 五 2025-10-10 15:42:24 CST; 5s ago
Docs: man:sshd(8)
man:sshd_config(5)
Main PID: 22551 (sshd)
Tasks: 1
CGroup: /system.slice/sshd.service
└─22551 /usr/sbin/sshd -D

http://www.dtcms.com/a/465382.html

相关文章:

  • 【PM2】PM2 集群模式适用的场景
  • 保定网站建设方案外包南宁网站建设哪
  • 做网站建设费用预算百度贴吧网站开发需求分析
  • Docker 仓库详解与实战配置
  • dockerfile实操案例
  • linux学习笔记(25)——线程安全
  • ubuntu20.04地平线OE3.2.0 GPU Docker使用
  • [VoiceRAG] Azure | 使用`azd`部署应用 | Dockerfile
  • Docker 环境下 GeoPandas/Fiona 报错
  • Docker简易教程
  • vps 网站发布直播软件app下载免费
  • DORIS 服务器宕机重启后出现的问题
  • 网络安全审计技术原理与应用
  • 手机上做网站南宁品牌网站设计公司
  • 第五部分:VTK高级功能模块(第135章 Imaging模块 - 图像处理类)
  • 如何通过 5 种有效方法同步 Android 和 Mac
  • AJAX 知识篇(2):Axios的核心配置
  • 招商网站建设公司申请注册商标的流程
  • 网页美工课程seo网站优化师
  • 海外关键词规划SEO工具
  • AI学习日记——卷积神经网络(CNN):卷积层与池化层的实现
  • iOS 26 系统流畅度实战指南|流畅体验检测|滑动顺畅对比
  • JS中new的过程发生了什么
  • 系统白名单接口添加自定义验证(模仿oauth2.0),防安全扫描不通过
  • 校园服装网站建设预算手机软件应用市场
  • 【AI论文】ExGRPO:从经验中学习进行推理
  • 连接两个世界:QIR——量子-经典混合计算的编译器桥梁
  • 怎样制作网页链接教程狼雨seo教程
  • 第1章:初识Linux系统——连接网络NAT模式
  • CSS3 动画:从入门到精通