在 Linux 系统中,服务管理脚本通常用于启动、停止、重启和查询系统服务的状态。
以下是一个使用 Bash 编写的简单服务管理脚本示例。
![Linux服务管理脚本有哪些(启动、停止、重启和查询系统服务的状态脚本) 图片[1]-Linux服务管理脚本有哪些(启动、停止、重启和查询系统服务的状态脚本)-不念博客](https://www.bunian.cn/wp-content/uploads/2023/04/u34619143374258179225fm253fmtautoapp138fJPEG.webp)
首先,创建一个名为 service_manager.sh
的脚本文件,并使用以下内容:
#!/bin/bashif [ $# -ne 2 ]; thenecho "用法:./service_manager.sh <start|stop|restart|status> <服务名>"exit 1fiACTION="$1"SERVICE="$2"function start_service() {sudo systemctl start $1echo "已启动 $1 服务。"}function stop_service() {sudo systemctl stop $1echo "已停止 $1 服务。"}function restart_service() {sudo systemctl restart $1echo "已重启 $1 服务。"}function status_service() {sudo systemctl status $1}case $ACTION instart)start_service $SERVICE;;stop)stop_service $SERVICE;;restart)restart_service $SERVICE;;status)status_service $SERVICE;;*)echo "未知操作:$ACTION"echo "用法:./service_manager.sh <start|stop|restart|status> <服务名>"exit 1;;esac#!/bin/bash if [ $# -ne 2 ]; then echo "用法:./service_manager.sh <start|stop|restart|status> <服务名>" exit 1 fi ACTION="$1" SERVICE="$2" function start_service() { sudo systemctl start $1 echo "已启动 $1 服务。" } function stop_service() { sudo systemctl stop $1 echo "已停止 $1 服务。" } function restart_service() { sudo systemctl restart $1 echo "已重启 $1 服务。" } function status_service() { sudo systemctl status $1 } case $ACTION in start) start_service $SERVICE ;; stop) stop_service $SERVICE ;; restart) restart_service $SERVICE ;; status) status_service $SERVICE ;; *) echo "未知操作:$ACTION" echo "用法:./service_manager.sh <start|stop|restart|status> <服务名>" exit 1 ;; esac#!/bin/bash if [ $# -ne 2 ]; then echo "用法:./service_manager.sh <start|stop|restart|status> <服务名>" exit 1 fi ACTION="$1" SERVICE="$2" function start_service() { sudo systemctl start $1 echo "已启动 $1 服务。" } function stop_service() { sudo systemctl stop $1 echo "已停止 $1 服务。" } function restart_service() { sudo systemctl restart $1 echo "已重启 $1 服务。" } function status_service() { sudo systemctl status $1 } case $ACTION in start) start_service $SERVICE ;; stop) stop_service $SERVICE ;; restart) restart_service $SERVICE ;; status) status_service $SERVICE ;; *) echo "未知操作:$ACTION" echo "用法:./service_manager.sh <start|stop|restart|status> <服务名>" exit 1 ;; esac
为脚本文件添加执行权限:
chmod +x service_manager.shchmod +x service_manager.shchmod +x service_manager.sh
使用以下命令运行脚本:
./service_manager.sh <操作> <服务名>./service_manager.sh <操作> <服务名>./service_manager.sh <操作> <服务名>
其中,<操作>
可以是 start(启动)、stop(停止)、restart(重启)或 status(查询状态),<服务名>
是您要管理的服务的名称,例如 apache2、mysql 等。
例如,要启动 Apache 服务,请运行:
./service_manager.sh start apache2./service_manager.sh start apache2./service_manager.sh start apache2
要查询 MySQL 服务的状态,请运行:
./service_manager.sh status mysql./service_manager.sh status mysql./service_manager.sh status mysql
请注意,此脚本需要管理员权限才能执行服务管理操作。
© 版权声明
本站文章由不念博客原创,未经允许严禁转载!
THE END