案例:通过脚本实现仅sshd、rsyslog、crond、network、sysstat服务在开机时自启动。
Linux系统在开机的服务通常工作在文本模式3级别,因此只需要查找3级别以上的开启的服务即可。查看命令:
chkconfig --list |grep 3:on
[root@vm1 ~]# chkconfig --list |grep 3:onNote: This output shows SysV services only and does not include nativesystemd services. SysV configuration data might be overridden by nativesystemd configuration.If you want to list systemd services use 'systemctl list-unit-files'.To see services enabled on particular target use'systemctl list-dependencies [target]'.network 0:off 1:off 2:on 3:on 4:on 5:on 6:off
[root@vm1 ~]#
默认情况下开启的服务比较少,只有network。
[root@vm1 ~]# for name in `chkconfig --list |grep 3:on|awk '{print $1}'`;do chkconfig --level 3 $name off;doneNote: This output shows SysV services only and does not include nativesystemd services. SysV configuration data might be overridden by nativesystemd configuration.If you want to list systemd services use 'systemctl list-unit-files'.To see services enabled on particular target use'systemctl list-dependencies [target]'.[root@vm1 ~]# for name in crond network rsyslog sshd sysstat;do chkconfig --level 3 $name on;done
Note: Forwarding request to 'systemctl enable crond.service'.
Note: Forwarding request to 'systemctl enable rsyslog.service'.
Note: Forwarding request to 'systemctl enable sshd.service'.
error reading information on service sysstat: No such file or directory[root@vm1 ~]# chkconfig --list |grep 3:on
说明:将默认开启的服务都关闭,然后开启需要开启的服务。
方法2:
[root@vm1 ~]# for name in `chkconfig --list|grep 3:on|awk '{print $1}'|grep -vE "crond|network|sshd|rsyslog|sysstat"`;do chkconfig $name off;doneNote: This output shows SysV services only and does not include nativesystemd services. SysV configuration data might be overridden by nativesystemd configuration.If you want to list systemd services use 'systemctl list-unit-files'.To see services enabled on particular target use'systemctl list-dependencies [target]'.
Linux系统管理员,需要遵循的原则是最小化原则,尽量不安装不使用的软件,尽量不开启不需要开启的服务,只要不用,就不开启。
我们再理解下for循环语句的结构。chkconfig命令获取到取值变量列表,然后for循环语句“遍历”这个列表,进行处理。