我正在尝试让 systemd 执行 init.d 脚本会执行的操作,即在手动发出启动或停止命令后自动显示服务的状态。这可能吗?
不幸的是,systemd 会立即弹回来,因为它在后台运行,然后您必须执行第二个命令来显示状态,启动或停止可能有效也可能无效,除非您询问,否则 systemd 不会告诉您,让您一无所知。
即我试图获得
service nginx status
在我完成
service nginx start
或者
service nginx restart
(或者在脑受损的 systemd 中, systemctl start nginx.service
)
答案1
我也需要它,所以我把它做成了一个shell脚本函数。
# Usage
# sc start nginx
# sc start nginx php74-php-fpm
function sc {
name="${@:(2)}";
echo "COMMAND: ${1}, NAME: ${name}";
systemctl "${1}" ${name};
systemctl status ${name};
}
减少命令输入过程如下。
#systemctl start nginx; systemctl status nginx
sc start nginx
这是在 CentOS 7 中添加到 /root/.basrc 的命令。
echo 'function sc { name="${@:(2)}"; echo "COMMAND: ${1}, NAME: ${name}"; systemctl "${1}" ${name}; systemctl status ${name}; }' >> ~/.bashrc && source ~/.bashrc
跑步sc start nginx
COMMAND: start, NAME: nginx
● nginx.service - nginx - high performance web server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
Active: active (running) since 토 2020-11-21 11:36:11 KST; 49s ago
Docs: http://nginx.org/en/docs/
Process: 31713 ExecStop=/bin/sh -c /bin/kill -s TERM $(/bin/cat /var/run/nginx.pid) (code=exited, status=0/SUCCESS)
Process: 31718 ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
Main PID: 31719 (nginx)
CGroup: /system.slice/nginx.service
├─31719 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
├─31720 nginx: worker process
├─31721 nginx: worker process
├─31722 nginx: worker process
├─31723 nginx: worker process
├─31724 nginx: worker process
└─31725 nginx: worker process
11월 21 11:36:11 dev5.php79.com systemd[1]: Starting nginx - high performance web server...
11월 21 11:36:11 dev5.php79.com systemd[1]: Started nginx - high performance web server.
要点 -https://gist.github.com/ibin79/4d1d0b5c48ebbc70730292a96ae367d9
答案2
没有适合您用例的内置命令,因此您必须为您最喜欢的 shell 或简单的脚本包装器创建一个别名。
答案3
为了使 systemd 更加“详细”,请在您的文件中添加/取消注释以下行/etc/systemd/journald.conf
,然后重新启动:
ForwardToConsole=yes
MaxLevelConsole=debug
答案4
一种解决方案是增加SYSTEMD_LOG_LEVEL
然后debug
过滤输出,例如:
$ SERVICES="smartmontools cron xxxxx"
$ SYSTEMD_LOG_LEVEL=debug systemctl restart $SERVICES 2>&1|egrep "Got result|Failed"
Failed to restart xxxxx.service: Unit xxxxx.service not found.
Got result done/Success for job cron.service
Got result done/Success for job smartmontools.service
您还可以添加前缀,例如
$ SYSTEMD_LOG_LEVEL=debug systemctl restart $SERVICES 2>&1|egrep -i "Got result|Failed"|sed 's,^,restart: ,'
restart: Failed to restart xxxxx.service: Unit xxxxx.service not found.
restart: Got result done/Success for job cron.service
restart: Got result done/Success for job smartmontools.service
SYSTEMD_LOG_LEVEL
可能并非在所有系统上都可用。