添加systemd服务,实现系统局域网唤醒功能Wake on LAN(wol)

时间:2020-03-21 11:42:35  来源:igfitidea点击:

如何在RHEL7或者CentOS7上设置Wake on LAN(wol)?
在RHEL7或者CentOS7上,ETHTOOL_OPTS已过时。不过我们可以添加UDEV规则和systemd服务来实现WOL。

ETHTOOL_OPTS已弃用

查看/usr/share/doc/initscripts*/sysconfig.txt并搜索ETHTOOL_OPTS,我们会发现:

Deprecated, but supported:
    ETHTOOL_OPTS=...
      Any device-specific options supported by ethtool. For example,
      if you wanted to force 100Mb full duplex:
        ETHTOOL_OPTS="speed 100 duplex full autoneg off"
      Note that changing speed or duplex settings almost always
      requires disabling autonegotiation with 'autoneg off'.

      Multiple options can also be set like so :
      ETHTOOL_OPTS="-K ${DEVICE} tso on; -G ${DEVICE} rx 256 tx 256"

      Long term, this should be done by sysadmin-written udev rules.

如您所见,不建议使用NIC配置文件(/etc/sysconfig/network-scripts/ifcfg-eth0)中的选项ETHTOOL_OPTS ="-s ${DEVICE} wol g",仍受支持。但是已经弃用了该选项。

他们说它仍然受支持,但是在许多RHEL7或者CentOS7系统上,该选项似乎在启动时未使用,导致无法启用局域网唤醒功能。

UDEV规则

我们可以为网络设备添加UDEV规则,以便在NIC在线时被激活。
首先找出网卡名称:

cat /proc/net/dev
enp0s25: 23399505   25169    0  0  0  0  0 2  2716146 20636  0 0 0 0 0  0
    lo:   12772     144    0  0  0  0 0  0 12772 144 0 0 0 0 0  0

为enp0s25添加一条udev规则,如果该设备在线,则要启动系统化的wakeonlan.service:

# cd /etc/udev/rules.d
# vi 99-wakeonlan
KERNEL="enp0s25", ACTION=="online", PROGRAM="/bin/systemctl start wakeonlan.service"

创建系统唤醒服务

创建一个名为systemd-wakeonlan的systemd脚本,用以停止和启动该服务:

# vi /usr/lib/systemd/systemd-wakeonlan
#!/bin/sh

# only usable for root
[ $EUID = 0 ] || exit 4

start() {
        ethtool -s enp0s25 wol g
}

stop() {
        ethtool -s enp0s25 wol d
}

case "" in
        start|stop) "" ;;
esac

添加可执行权限:

# chmod +x /usr/lib/systemd/systemd-wakeonlan

添加服务文件:

# vi /usr/lib/systemd/system/wakeonlan.service
[Unit]
Description=Configure Wake-up on LAN

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/lib/systemd/systemd-wakeonlan start
ExecStop=/usr/lib/systemd/systemd-wakeonlan stop

[Install]
WantedBy=basic.target

启用服务,以便它在重新启动后也可以工作(chkconfig是RHEL6上的命令):

# systemctl enable wakeonlan.service
ln -s '/usr/lib/systemd/system/wakeonlan.service'\
'/etc/systemd/system/basic.target.wants/wakeonlan.service'

现在已启动该服务,可以使用systemctl停止和启动Wake on LAN服务。

# systemctl stop wakeonlan.service
or
# systemctl start wakeonlan.service
or
# systemctl status wakeonlan.service

如果您一切正常,则该服务将启动,而不会出现任何警告或者错误。
现在重新引导系统,并在重新引导后使用ethtool检查服务是否在引导时自动启动。

# ethtool enp0s25

在我们的情况下,"唤醒"选项应为g(从magicpacket唤醒后开始)。

通过联网和断网来检查系统是否能被唤醒。