4

systemd的几个妙用

 7 months ago
source link: https://www.bboy.app/2024/02/04/systemd%E7%9A%84%E5%87%A0%E4%B8%AA%E5%A6%99%E7%94%A8/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

systemd的几个妙用

February 4, 2024 本文有 1108 个字 需要花费 3 分钟阅读
20240204-1.webp

systemd不仅可以管理系统中的各个服务,还具有许多有趣和实用的功能。在这篇博客中,我将向你介绍如何使用systemd进行时间同步,磁盘挂载和执行定时任务。

时间同步:使用systemd-timesyncd

systemd-timesyncd是一个简单的网络时间同步守护程序,你可以用它来同步你的系统时间。首先,我们需要禁用本机的NTP服务,例如我本机使用的chrony:

systemctl disable chrony && systemctl stop  chrony

然后,我们可以使用timedatectl status命令来查看本机的NTP服务状态。接着,我们需要检查systemd-timesyncd服务的状态:

systemctl status systemd-timesyncd

如果你看到以下输出:

○ systemd-timesyncd.service
     Loaded: masked (Reason: Unit systemd-timesyncd.service is masked.)
     Active: inactive (dead)

这表示你的服务被屏蔽了。要取消屏蔽,输入以下命令:

systemctl unmask systemd-timesyncd

接着启动服务:

systemctl start systemd-timesyncd

如果提示Failed to start systemd-timesyncd.service: Unit systemd-timesyncd.service not found.,表示你系统中的systemd-timesyncd包未安装,可以通过以下命令进行安装:

apt-get install systemd-timesyncd

安装完成后,启动服务:

systemctl start systemd-timesyncd

如果你想修改NTP服务器,可以编辑/etc/systemd/timesyncd.conf文件:

vim /etc/systemd/timesyncd.conf
[Time]
NTP=cn.ntp.org.cn

最后,重启服务并配置为开机启动:

systemctl restart systemd-timesyncd
systemctl enable systemd-timesyncd

最后查看状态

timedatectl

磁盘挂载:使用systemd挂载NFS

要使用systemd挂载磁盘,你需要创建一个.mount文件。例如,我们创建一个名为root-test.mount的文件:

vim /etc/systemd/system/root-test.mount

并添加以下内容:

[Unit]
Description=Mount NFS

[Mount]
What=10.10.100.244:/volume1/data
Where=/root/test
Type=nfs
Options=defaults

[Install]
WantedBy=multi-user.target

注意,.mount文件的文件名必须与挂载的路径相符。例如,如果挂载的路径地址是/root/test,那么文件的名字就必须是root-test.mount。否则,你会看到如下错误信息:

nfs-test.mount: Where= setting doesn't match unit name. Refusing.

创建完成后,使用以下命令启动挂载:

systemctl start root-test.mount

你可以使用systemctl stop root-test.mount命令来卸载文件系统,使用systemctl enable root-test.mount命令来设置开机启动挂载。

执行定时任务:使用systemd定时器

systemd还可以配置用来执行定时任务。首先,我们需要创建一个service。例如,我们创建一个名为date.service的文件:

vim /etc/systemd/system/date.service

并添加以下内容:

[Unit]
Description=log date
Wants=logdate.timer

[Service]
Type=oneshot
ExecStart=sh -c 'date > /var/date.log'

[Install]
WantedBy=multi-user.target

你可以使用systemctl status logdate命令来查看服务状态。

接着,我们需要创建一个定时器。例如,我们创建一个名为logdate.timer的文件:

vim /etc/systemd/system/logdate.timer

并添加以下内容:

[Unit]
Description=Exec logmemory
Requires=date.service

[Timer]
Unit=date.service
OnCalendar=*-*-* *:*:00

[Install]
WantedBy=timers.target

我在这里配置的是每分钟执行一次logmemory.service这个服务。

启动这个定时器:

systemctl start logdate.timer

你可以使用systemctl status logdate.timer命令来查看定时器状态。

欢迎关注我的博客www.bboy.app

Have Fun


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK