文章目录

  • iptables规则备份和恢复
  • firewalld的9个zone
  • firewalld关于zone的操作
  • firewalld关于service的操作
  • linux任务计划cron
  • chkconfig工具
  • systemd管理服务
  • unit介绍
  • target介绍


iptables规则备份和恢复

设定的防火墙规则只是保存在内存中,并没有保存到配置文件中,也就说当系统重启后以前设定的规则就没有了,所以设定好规则后要先保存规则,以免重启后规则丢失。

  • 保存和备份iptables规则
    service iptables save //会把规则保存到/etc/sysconfig/iptables
[root@linux7-128 ~]# service iptables save
iptables: Saving firewall rules to /etc/sysconfig/iptables:[  确定  ]
  • 把iptables规则备份到my.ipt文件中
    iptables-save > my.ipt
[root@linux7-128 ~]# iptables-save > /tmp/my.txt
[root@linux7-128 ~]# cat /tmp/my.txt 
# Generated by iptables-save v1.4.21 on Tue Jun 12 19:16:51 2018
*mangle
:PREROUTING ACCEPT [277:25577]
:INPUT ACCEPT [277:25577]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [239:28886]
:POSTROUTING ACCEPT [248:30809]
-A POSTROUTING -o virbr0 -p udp -m udp --dport 68 -j CHECKSUM --checksum-fill
COMMIT
# Completed on Tue Jun 12 19:16:51 2018
# Generated by iptables-save v1.4.21 on Tue Jun 12 19:16:51 2018
*nat
:PREROUTING ACCEPT [31:3306]
:INPUT ACCEPT [1:60]
:OUTPUT ACCEPT [98:7544]
:POSTROUTING ACCEPT [98:7544]
-A POSTROUTING -s 192.168.122.0/24 -d 224.0.0.0/24 -j RETURN
-A POSTROUTING -s 192.168.122.0/24 -d 255.255.255.255/32 -j RETURN
-A POSTROUTING -s 192.168.122.0/24 ! -d 192.168.122.0/24 -p tcp -j MASQUERADE --to-ports 1024-65535
-A POSTROUTING -s 192.168.122.0/24 ! -d 192.168.122.0/24 -p udp -j MASQUERADE --to-ports 1024-65535
-A POSTROUTING -s 192.168.122.0/24 ! -d 192.168.122.0/24 -j MASQUERADE
COMMIT
# Completed on Tue Jun 12 19:16:51 2018
# Generated by iptables-save v1.4.21 on Tue Jun 12 19:16:51 2018
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [239:28886]
-A INPUT -i virbr0 -p udp -m udp --dport 53 -j ACCEPT
-A INPUT -i virbr0 -p tcp -m tcp --dport 53 -j ACCEPT
-A INPUT -i virbr0 -p udp -m udp --dport 67 -j ACCEPT
-A INPUT -i virbr0 -p tcp -m tcp --dport 67 -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -d 192.168.122.0/24 -o virbr0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -s 192.168.122.0/24 -i virbr0 -j ACCEPT
-A FORWARD -i virbr0 -o virbr0 -j ACCEPT
-A FORWARD -o virbr0 -j REJECT --reject-with icmp-port-unreachable
-A FORWARD -i virbr0 -j REJECT --reject-with icmp-port-unreachable
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
-A OUTPUT -o virbr0 -p udp -m udp --dport 68 -j ACCEPT
COMMIT
# Completed on Tue Jun 12 19:16:51 2018

-恢复刚才备份的规则
iptables-restore < my.ipt

[root@linux7-128 ~]# iptables-restore < /tmp/my.txt

当系统开机或者重启时,就想要加载一些规则,那么最好把规则放到/etc/sysconfig/iptables里,放到这里可以先保存。

//通过iptables-restore规则集到数据包过滤表中

[root@lanquark ~]# iptables-restore iptables-script 
[root@lanquark ~]# iptables -nvL
Chain INPUT (policy ACCEPT 2 packets, 986 bytes)
 pkts bytes target     prot opt in     out     source               destination         
   21  1412 ACCEPT     tcp  --  *      *       192.168.1.9          0.0.0.0/0            tcp dpt:22

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         

Chain OUTPUT (policy ACCEPT 12 packets, 1152 bytes)
 pkts bytes target     prot opt in     out     source               destination

firewalld的9个zone

centos7以及以后的版本使用的防火墙为firewalld

  • 打开firewalld
//取消iptables的开机启动
[root@linux7-128 ~]# systemctl disable iptables
Removed symlink /etc/systemd/system/basic.target.wants/iptables.service.
//停止iptables防火墙
[root@linux7-128 ~]# systemctl stop iptables
//验证iptables的状态已关闭
[root@lanquark ~]# systemctl status iptables.service 
● iptables.service - IPv4 firewall with iptables
   Loaded: loaded (/usr/lib/systemd/system/iptables.service; disabled; vendor preset: disabled)
   Active: inactive (dead) since Thu 2018-06-14 22:29:10 CST; 41s ago
 Main PID: 731 (code=exited, status=0/SUCCESS)

Jun 13 19:50:33 lanquark.com systemd[1]: Starting IPv4 firewall with iptables...
Jun 13 19:50:33 lanquark.com iptables.init[731]: iptables: Applying firewall rules: [  OK  ]
Jun 13 19:50:33 lanquark.com systemd[1]: Started IPv4 firewall with iptables.
Jun 14 22:29:09 lanquark.com systemd[1]: Stopping IPv4 firewall with iptables...
Jun 14 22:29:09 lanquark.com iptables.init[3516]: iptables: Setting chains to policy ACCEPT: nat filter [  OK  ]
Jun 14 22:29:09 lanquark.com iptables.init[3516]: iptables: Flushing firewall rules: [  OK  ]
Jun 14 22:29:10 lanquark.com iptables.init[3516]: iptables: Unloading modules: [  OK  ]
Jun 14 22:29:10 lanquark.com systemd[1]: Stopped IPv4 firewall with iptables.
//将firewalld设为开机启动
[root@linux7-128 ~]# systemctl enable firewalld
Created symlink from /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service to /usr/lib/systemd/system/firewalld.service.
Created symlink from /etc/systemd/system/multi-user.target.wants/firewalld.service to /usr/lib/systemd/system/firewalld.service.
//启动firewalld
[root@linux7-128 ~]# systemctl start firewalld
//验证firewalld状态
[root@lanquark ~]# systemctl status firewalld.service 
● firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2018-06-14 22:30:19 CST; 3min 6s ago
     Docs: man:firewalld(1)
 Main PID: 3726 (firewalld)
   CGroup: /system.slice/firewalld.service
           └─3726 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid

Jun 14 22:30:18 lanquark.com systemd[1]: Starting firewalld - dynamic firewall daemon...
Jun 14 22:30:19 lanquark.com systemd[1]: Started firewalld - dynamic firewall daemon.
Jun 14 22:30:19 lanquark.com firewalld[3726]: WARNING: ICMP type 'beyond-scope' is not supported by the kernel for ipv6.
Jun 14 22:30:19 lanquark.com firewalld[3726]: WARNING: beyond-scope: INVALID_ICMPTYPE: No supported ICMP type., ignorin...-time.
Jun 14 22:30:19 lanquark.com firewalld[3726]: WARNING: ICMP type 'failed-policy' is not supported by the kernel for ipv6.
Jun 14 22:30:19 lanquark.com firewalld[3726]: WARNING: failed-policy: INVALID_ICMPTYPE: No supported ICMP type., ignori...-time.
Jun 14 22:30:19 lanquark.com firewalld[3726]: WARNING: ICMP type 'reject-route' is not supported by the kernel for ipv6.
Jun 14 22:30:19 lanquark.com firewalld[3726]: WARNING: reject-route: INVALID_ICMPTYPE: No supported ICMP type., ignorin...-time.
Hint: Some lines were ellipsized, use -l to show in full.

使用iptables -nvL发现规则变多了,这些就是firewalld自带的规则。

  • firewalld默认有9个zone
    zone是firewalld的一个单位

默认zone为public,每个zone好比一个规则集,自带一些规则。

  • 查看所有zone
    firewall-cmd --get-zones
[root@linux7-128 ~]#  firewall-cmd --get-zones 
block dmz drop external home internal public trusted work
  • 查看默认zone
    firewall-cmd --get-default-zone
[root@linux7-128 ~]# firewall-cmd --get-default-zone
public
  • 9个zone区别
drop(丢弃):任何接受的网络数据包都被丢弃,没有任何恢复,仅能有发送出去的网络连接(数据包不能进来,但是可以出去)
block(限制):任何接受的网络连接都被IPv4的icmp-host-prohibited信息和IPv6的icmp6-adm-prohibited信息所拒绝。(和drop相比,比较宽松一些,主要是为了针对icmp)
piblic(公共):在公共区域内使用,不能相信网络内其他计算机不会对你造成危害,只能接受经过选取的连接。
external(外部):特别是为路由器启用了伪装功能的外部网,你不能信任来自网络的其他计算,不能相信他们不会对你造成伤害,只能接受经过选择的连接。
dmz(非军事区):用于你的非军事区内的电脑,此区域可公开访问,可以有限的进入你的内部网络,仅仅接受经过选择的连接。
work(工作):用于工作区,你可以基本信任网络内的其他电脑不会对你造成危害,仅仅接收经过选择的连接。
home(家庭):用于内部网络,你可以基本上信任网络内其他电脑不会对你造成危害,仅仅接收经过选择的连接。
internal(内部):用于内部网络,你可以基本上信任网络内其他电脑不会对你造成危害,仅仅接收经过选择的连接。
trusted(信任):可接受所有的网络连接。

firewalld关于zone的操作

  • 设定默认zone
    firewall-cmd --set-default-zone=work
[root@linux7-128 ~]# firewall-cmd --set-default-zone=work
success
[root@linux7-128 ~]# firewall-cmd --get-default-zone 
work
  • 查指定网卡
    firewall-cmd --get-zone-of-interface=ens33
[root@linux7-128 ~]#  firewall-cmd --get-zone-of-interface=ens33 
work
[root@linux7-128 ~]#  firewall-cmd --get-zone-of-interface=ens33:0
no zone
[root@linux7-128 ~]#  firewall-cmd --get-zone-of-interface=lo
no zone
  • 给指定网卡设置zone
    firewall-cmd --zone=public --add-interface=lo
[root@linux7-128 network-scripts]# firewall-cmd --zone=public --add-interface=ens33:0
success
[root@linux7-128 network-scripts]#  firewall-cmd --get-zone-of-interface=ens33:0
public
  • 针对网卡更改zone
    firewall-cmd --zone=dmz --change-interface=lo
[root@linux7-128 network-scripts]# firewall-cmd --zone=dmz --change-interface=ens33:0
success
[root@linux7-128 network-scripts]#  firewall-cmd --get-zone-of-interface=ens33:0
dmz
  • 针对网卡删除zone
    firewall-cmd --zone=dmz --remove-interface=lo
[root@linux7-128 network-scripts]#  firewall-cmd --zone=dmz  --remove-interface=ens33:0
success
[root@linux7-128 network-scripts]#  firewall-cmd --get-zone-of-interface=ens33:0
no zone
  • 查看系统所有网卡所在的zone
    firewall-cmd --get-active-zones
[root@linux7-128 network-scripts]# firewall-cmd --get-active-zones  
work
  interfaces: ens33
public
  interfaces: lo

firewalld关于service的操作

service:zone下面的一个子单元,可以理解成里面的一个端口

  • 查看所有的servies
    firewall-cmd --get-service(s)
[root@linux7-128 ~]# firewall-cmd --get-service 
RH-Satellite-6 amanda-client amanda-k5-client bacula bacula-client bitcoin 
bitcoin-rpc bitcoin-testnet bitcoin-testnet-rpc ceph ceph-mon cfengine 
condor-collector ctdb dhcp dhcpv6 dhcpv6-client dns docker-registry dropbox-
lansync elasticsearch freeipa-ldap freeipa-ldaps freeipa-replication freeipa-
trust ftp ganglia-client ganglia-master high-availability http https imap 
imaps ipp ipp-client ipsec iscsi-target kadmin kerberos kibana klogin kpasswd
 kshell ldap ldaps libvirt libvirt-tls managesieve mdns mosh mountd ms-wbt
 mssql mysql nfs nrpe ntp openvpn ovirt-imageio ovirt-storageconsole ovirt-
vmconsole pmcd pmproxy pmwebapi pmwebapis pop3 pop3s postgresql privoxy
 proxy-dhcp ptp pulseaudio puppetmaster quassel radius rpc-bind rsh rsyncd
 samba samba-client sane sip sips smtp smtp-submission smtps snmp snmptrap
 spideroak-lansync squid ssh synergy syslog syslog-tls telnet tftp tftp-
client tinc tor-socks transmission-client vdsm vnc-server wbem-https xmpp-
bosh xmpp-client xmpp-local xmpp-server

services也可以写成service

  • 查看当前zone下有哪些service
    firewall-cmd --list-services
[root@linux7-128 ~]# firewall-cmd --get-default-zone 
work
[root@linux7-128 ~]# firewall-cmd --list-services  
ssh dhcpv6-client
[root@linux7-128 ~]# firewall-cmd --list-service
ssh dhcpv6-client
  • 查看指定zone下有哪些service
    firewall-cmd --zone=public --list-service
[root@linux7-128 ~]# firewall-cmd --zone=public --list-service
ssh dhcpv6-client
[root@linux7-128 ~]# firewall-cmd --zone=block --list-service

空
  • 把http增加到public zone下面
    firewall-cmd --zone=public --add-service=http
[root@linux7-128 ~]# firewall-cmd --zone=public --add-service=http
success
[root@linux7-128 ~]# firewall-cmd --zone=public --list-services 
ssh dhcpv6-client http
  • 更改配置文件
    firewall-cmd --zone=public --add-service=http --permanent
    之后会在/etc/firewalld/zones目录下面生成配置文件
[root@linux7-128 ~]# firewall-cmd --zone=public --add-service=http --permanent
success
[root@linux7-128 ~]# ls /etc/firewalld/zones
public.xml  public.xml.old
[root@linux7-128 ~]# cat /etc/firewalld/zones/public.xml
<?xml version="1.0" encoding="utf-8"?>
<zone>
  <short>Public</short>
  <description>For use in public areas. You do not trust the other computers on networks to not harm your computer. Only selected incoming connections are accepted.</description>
  <service name="ssh"/>
  <service name="dhcpv6-client"/>
  <service name="http"/>
</zone>

如果这时候在增加一个ftp,他是不会再配置文件里的,因为没有用 --permanent,使用permanent永久保存之后,在新增一个,会生成一个old文件将旧的保存下来。

  • zone的配置文件模板
    ls /usr/lib/firewalld/zones/

/etc/firewalld/zones里面的文件都是有模板的,这些模板在/usr/lib/firewalld/zones/里
/etc/firewalld/services里面也有模板,在/usr/lib/firewalld/services/下

[root@linux7-128 ~]# ls /usr/lib/firewalld/zones/
block.xml  dmz.xml  drop.xml  external.xml  home.xml  internal.xml  public.xml  trusted.xml  work.xml
[root@linux7-128 ~]# ls /usr/lib/firewalld/services/
amanda-client.xml        freeipa-replication.xml  libvirt-tls.xml           postgresql.xml       spideroak-lansync.xml
amanda-k5-client.xml     freeipa-trust.xml        libvirt.xml               privoxy.xml          squid.xml
bacula-client.xml        ftp.xml                  managesieve.xml           proxy-dhcp.xml       ssh.xml
bacula.xml               ganglia-client.xml       mdns.xml                  ptp.xml              synergy.xml
bitcoin-rpc.xml          ganglia-master.xml       mosh.xml                  pulseaudio.xml       syslog-tls.xml
bitcoin-testnet-rpc.xml  high-availability.xml    mountd.xml                puppetmaster.xml     syslog.xml
bitcoin-testnet.xml      https.xml                mssql.xml                 quassel.xml          telnet.xml
bitcoin.xml              http.xml                 ms-wbt.xml                radius.xml           tftp-client.xml
ceph-mon.xml             imaps.xml                mysql.xml                 RH-Satellite-6.xml   tftp.xml
ceph.xml                 imap.xml                 nfs.xml                   rpc-bind.xml         tinc.xml
cfengine.xml             ipp-client.xml           nrpe.xml                  rsh.xml              tor-socks.xml
condor-collector.xml     ipp.xml                  ntp.xml                   rsyncd.xml           transmission-client.xml
ctdb.xml                 ipsec.xml                openvpn.xml               samba-client.xml     vdsm.xml
dhcpv6-client.xml        iscsi-target.xml         ovirt-imageio.xml         samba.xml            vnc-server.xml
dhcpv6.xml               kadmin.xml               ovirt-storageconsole.xml  sane.xml             wbem-https.xml
dhcp.xml                 kerberos.xml             ovirt-vmconsole.xml       sips.xml             xmpp-bosh.xml
dns.xml                  kibana.xml               pmcd.xml                  sip.xml              xmpp-client.xml
docker-registry.xml      klogin.xml               pmproxy.xml               smtp-submission.xml  xmpp-local.xml
dropbox-lansync.xml      kpasswd.xml              pmwebapis.xml             smtps.xml            xmpp-server.xml
elasticsearch.xml        kshell.xml               pmwebapi.xml              smtp.xml
freeipa-ldaps.xml        ldaps.xml                pop3s.xml                 snmptrap.xml
freeipa-ldap.xml         ldap.xml                 pop3.xml                  snmp.xml

需求
ftp服务自定义端口1121,需要在work zone下面放行ftp

1.首先需要将/usr/lib/firewalld/services/ftp.xml拷贝到/etc/firewalld/services去

[root@linux7-128 ~]# cp /usr/lib/firewalld/services/ftp.xml /etc/firewalld/services/

2.然后编辑/etc/firewalld/services/ftp.xml,将端口更改为1121

[root@linux7-128 ~]# vi /etc/firewalld/services/ftp.xml 

<?xml version="1.0" encoding="utf-8"?>
<service>
  <short>FTP</short>
  <description>FTP is a protocol used for remote file transfer. If you plan to make your FTP server publicly available, enable this option. You need the vsftpd package installed for this option to be useful.</description>
  <port protocol="tcp" port="1121"/>
  <module name="nf_conntrack_ftp"/>
</service>
~                                                                                                                        
~                                                                                                                        
~                                                                                                                        
~                                                                                                                        
~                                                                                                                        
~                                                                                                                        
~                                                                                                                        
~                                                                                                                        
~                                                                                                                        
~                                                                                                                        
~                                                                                                                        
~                                                                                                                        
-- INSERT --

3.将/usr/lib/firewalld/zones/work.xml复制到/etc/firewalld/zones下

[root@linux7-128 ~]# cp /usr/lib/firewalld/zones/work.xml /etc/firewalld/zones/

4.编辑/etc/firewalld/zones/work.xml,将ftp添加到work中去

[root@linux7-128 ~]# vim /etc/firewalld/zones/work.xml 

<?xml version="1.0" encoding="utf-8"?>
<zone>
  <short>Work</short>
  <description>For use in work areas. You mostly trust the other computers on networks to not harm your computer. Only selected incoming connections are accepted.</description>
  <service name="ssh"/>
  <service name="dhcpv6-client"/>
  <service name="ftp"/>
</zone>
~                                                                                                                        
~                                                                                                                        
~                                                                                                                        
                                                                                                                     
-- 插入 --                                                                                             8,8          全部

5.重新加载 firewall-cmd --reload

[root@linux7-128 ~]# firewall-cmd --reload 
success

6.查看work下的service

[root@linux7-128 ~]#  firewall-cmd --zone=work --list-services
ssh dhcpv6-client ftp

linux任务计划cron

  • 查看配置文件
[root@linux7-128 ~]# cat /etc/crontab 
SHELL=/bin/bash  --shell
PATH=/sbin:/bin:/usr/sbin:/usr/bin  --环境变量,命令路径
MAILTO=root  --发送邮件给谁

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

5个*位分别表示分 时 日 月 周 ,后面表示用户(user-name)和要执行的命令(command to be executed)

  • 写一个任务计划
    crontab -e

用法和vim类似,使用i编辑文件

0 22 * * * /usr/bin/top >>/tmp/123.log 2>>/tmp/123.log
在每天22点执行top命令并将正确信息和错误信息输出到/tmp/123.log里,*表示全部,每周每月每天。

可用格式1-5表示一个范围1到5
可用格式1,2,3表示1或者2或者3
可用格式*/2表示被2整除的数字,比如小时,那就是每隔2小时

0 22 1-10 */2 2,5 /bin/bash /usr/local/sbin/123.sh >>/tmp/123.log 2>>/tmp/123.log 每隔两个月的1-10号,周二或者周五,22点执行一个脚本并将结果输出到tmp/123.log里

**要确定某一天的唯一性,比如明年,可以用星期指定,因为明年的星期和今年是不一样的,这样就可以确定时间的唯一性 **

  • 要保证服务是启动状态
    systemctl start crond.service
[root@linux7-128 ~]# systemctl start crond.service
[root@linux7-128 ~]# ps aux |grep cron
root       939  0.0  0.1 126280  1620 ?        Ss   18:27   0:00 /usr/sbin/crond -n
root      4451  0.0  0.0 112720   984 pts/0    S+   21:24   0:00 grep --color=auto cron

使用ps aux |grep cron查看是否启动成功,第一条显示说明已经启动成功了。

也可以使用systemctl status crond查看,如果是绿色,表示启动成功,如果停止是没有颜色的。

[root@linux7-128 ~]# systemctl status crond
● crond.service - Command Scheduler
   Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled; vendor preset: enabled)
   Active: active (running) since 二 2018-06-12 18:27:56 CST; 2h 58min ago
 Main PID: 939 (crond)
   CGroup: /system.slice/crond.service
           └─939 /usr/sbin/crond -n

6月 12 18:27:56 linux7-128 systemd[1]: Started Command Scheduler.
6月 12 18:27:56 linux7-128 systemd[1]: Starting Command Scheduler...
6月 12 18:27:56 linux7-128 crond[939]: (CRON) INFO (RANDOM_DELAY will be scaled with factor 38% if used.)
6月 12 18:27:56 linux7-128 crond[939]: (CRON) INFO (running with inotify support)
  • 由于没有使用绝对路径而导致的计划没有执行

有时候,一些设置的计划并没有执行,可能就是因为脚本里的命令没有使用绝对路径,要想计划生效,需要将脚本里的命令使用绝对路径,或者在crond的配置文件里环境变量定义所使用的命令路径,才会生效。建议每个计划都要写上追加日志,这样方便我们排查问题。

  • 查看设置的计划
    crontab -l
[root@linux7-128 ~]# crontab -l
0 22 12 6 * /usr/bin/top >/tmp/1.log 2> /tmp/1/log

文件位于:/var/spool/cron/username

[root@linux7-128 ~]# cat /var/spool/cron/root
0 22 12 6 * /usr/bin/top >/tmp/1.log 2> /tmp/1/log
  • 备份计划

拷贝/var/spool/cron/username文件即可

  • 删除计划
    crontab -r
[root@linux7-128 ~]# crontab -r
[root@linux7-128 ~]# crontab -l
no crontab for root
  • 指定用户
    crontab -u
[root@linux7-128 ~]# crontab -u root -l
no crontab for root

chkconfig工具

系统服务管理

centos6以前使用chkconfig,centos7以后不用了,但是依旧兼容。

  • 查看系统使用chkconfig工具的服务有哪些
    chkconfig --list
[root@linux7-128 ~]# chkconfig --list

注:该输出结果只显示 SysV 服务,并不包含
原生 systemd 服务。SysV 配置数据
可能被原生 systemd 配置覆盖。 

      要列出 systemd 服务,请执行 'systemctl list-unit-files'。
      查看在具体 target 启用的服务请执行
      'systemctl list-dependencies [target]'。

netconsole     	0:关	1:关	2:关	3:关	4:关	5:关	6:关
network        	0:关	1:关	2:开	3:开	4:开	5:开	6:关

centos6及以前使用的sysV服务,centos7级以后使用的是systemd服务

服务存放路径:/etc/init.d/

[root@linux7-128 ~]# ls /etc/init.d/
functions  netconsole  network  README
  • 对服务进行开关
    chkconfig network off
    chkconfig network on
[root@linux7-128 ~]# chkconfig network off
[root@linux7-128 ~]# chkconfig --list

netconsole     	0:关	1:关	2:关	3:关	4:关	5:关	6:关
network        	0:关	1:关	2:关	3:关	4:关	5:关	6:关
[root@linux7-128 ~]# chkconfig network on
[root@linux7-128 ~]# chkconfig --list

netconsole     	0:关	1:关	2:关	3:关	4:关	5:关	6:关
network        	0:关	1:关	2:开	3:开	4:开	5:开	6:关

在6及6之前,系统运行级别有7个。
0 关机
1 单用户
2 多用户模式,不带图形,没有nfs服务(网络文件系统)
3 多用户模式,不带图形
4 保留级别
5 多用户模式,带图形
6 重启

在6及之前,可以定义/etc/inittab定义系统级别 ,7系统已经不在使用。

  • 指定某一个级别关闭
    chkconfig --level 3 network off
[root@linux7-128 ~]# chkconfig --level 3 network off 
[root@linux7-128 ~]# chkconfig --list


netconsole     	0:关	1:关	2:关	3:关	4:关	5:关	6:关
network        	0:关	1:关	2:开	3:关	4:开	5:开	6:关

多个级别不需要加逗号,使用chkconfig --level 345 network off

  • 把一个脚本加入到服务列表里

1.自定义一个脚本

[root@linux7-128 ~]# cd /etc/init.d/
[root@linux7-128 init.d]# ls
functions  netconsole  network  README
[root@linux7-128 init.d]# cp network 123
[root@linux7-128 init.d]# ls
123  functions  netconsole  network  README

2.把123加入到服务列表

[root@linux7-128 init.d]# chkconfig --add 123
[root@linux7-128 init.d]# chkconfig --list

注:该输出结果只显示 SysV 服务,并不包含
原生 systemd 服务。SysV 配置数据
可能被原生 systemd 配置覆盖。 

      要列出 systemd 服务,请执行 'systemctl list-unit-files'。
      查看在具体 target 启用的服务请执行
      'systemctl list-dependencies [target]'。

123            	0:关	1:关	2:开	3:开	4:开	5:开	6:关
netconsole     	0:关	1:关	2:关	3:关	4:关	5:关	6:关
network        	0:关	1:关	2:开	3:关	4:开	5:开	6:关

名称无所谓,但是文件内容有要求,首先是一个shell脚本,而且必须在/etc/init.d/目录下

[root@linux7-128 init.d]# vim 123

#! /bin/bash
#
# network       Bring up/down networking
#
(# chkconfig: 2345 10 90
# description: Activates/Deactivates all network interfaces configured to \
#              start at boot time.
#)
### BEGIN INIT INFO
# Provides: $network
# Should-Start: iptables ip6tables NetworkManager-wait-online NetworkManager $network-pre
# Short-Description: Bring up/down networking
# Description: Bring up/down networking
### END INIT INFO

# Source function library.
. /etc/init.d/functions

if [ ! -f /etc/sysconfig/network ]; then
    exit 6
"123" 250L, 7293C

括号括起来的部分必须有才可以识别出来,10表示第10位启动,90表示第90位关闭。

  • 删除一个服务
    chkconfig --del 123
[root@linux7-128 init.d]# chkconfig --del 123
[root@linux7-128 init.d]# chkconfig --list

注:该输出结果只显示 SysV 服务,并不包含
原生 systemd 服务。SysV 配置数据
可能被原生 systemd 配置覆盖。 

      要列出 systemd 服务,请执行 'systemctl list-unit-files'。
      查看在具体 target 启用的服务请执行
      'systemctl list-dependencies [target]'。

netconsole     	0:关	1:关	2:关	3:关	4:关	5:关	6:关
network        	0:关	1:关	2:开	3:关	4:开	5:开	6:关

systemd管理服务

  • 查看系统服务
    systemctl list-unit-files
[root@linux7-128 ~]# systemctl list-unit-files
UNIT FILE                                     STATE   
proc-sys-fs-binfmt_misc.automount             static  
dev-hugepages.mount                           static  
dev-mqueue.mount                              static  
proc-fs-nfsd.mount                            static  
proc-sys-fs-binfmt_misc.mount                 static  
sys-fs-fuse-connections.mount                 static  
sys-kernel-config.mount                       static  
sys-kernel-debug.mount                        static  
tmp.mount                                     disabled
var-lib-nfs-rpc_pipefs.mount                  static  
brandbot.path                                 disabled
cups.path                                     enabled 
systemd-ask-password-console.path             static  
systemd-ask-password-plymouth.path            static  
systemd-ask-password-wall.path                static  
session-6.scope                               static  
abrt-ccpp.service                             enabled 
abrt-oops.service                             enabled 
abrt-pstoreoops.service                       disabled
lines 1-20

显示前20行,按q退出

  • 只显示类型为service的服务
    systemctl list-units --all --type=service
[root@linux7-128 ~]# systemctl list-units --all --type=service
  UNIT                                            LOAD      ACTIVE   SUB     DESCRIPTION
  abrt-ccpp.service                               loaded    active   exited  Install ABRT coredump hook
  abrt-oops.service                               loaded    active   running ABRT kernel log watcher
  abrt-vmcore.service                             loaded    inactive dead    Harvest vmcores for ABRT
  abrt-xorg.service                               loaded    active   running ABRT Xorg log watcher
  abrtd.service                                   loaded    active   running ABRT Automated Bug Reporting Tool
  accounts-daemon.service                         loaded    inactive dead    Accounts Service
  alsa-restore.service                            loaded    inactive dead    Save/Restore Sound Card State
  alsa-state.service                              loaded    active   running Manage Sound Card State (restore and store)
● apparmor.service                                not-found inactive dead    apparmor.service
  atd.service                                     loaded    active   running Job spooling tools
  auditd.service                                  loaded    active   running Security Auditing Service
  auth-rpcgss-module.service                      loaded    inactive dead    Kernel Module supporting RPCSEC_GSS
  avahi-daemon.service                            loaded    active   running Avahi mDNS/DNS-SD Stack
  blk-availability.service                        loaded    active   exited  Availability of block devices
  brandbot.service                                loaded    inactive dead    Flexible Branding Service
  chronyd.service                                 loaded    active   running NTP client/server
  cpupower.service                                loaded    inactive dead    Configure CPU power related settings
  crond.service                                   loaded    active   running Command Scheduler
  cups.service                                    loaded    active   running CUPS Printing Service
lines 1-20
按空格继续往下翻
LOAD   = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB    = The low-level unit activation state, values depend on unit type.

143 loaded units listed.
To show all installed unit files use 'systemctl list-unit-files'.

这样显示比较清晰一点,还会显示描述信息

如果不加all就会只显示active ,不会显示 inactive

[root@linux7-128 ~]# systemctl list-units  --type=service
  UNIT                               LOAD   ACTIVE SUB     DESCRIPTION
  abrt-ccpp.service                  loaded active exited  Install ABRT coredump hook
  abrt-oops.service                  loaded active running ABRT kernel log watcher
  abrt-xorg.service                  loaded active running ABRT Xorg log watcher
  abrtd.service                      loaded active running ABRT Automated Bug Reporting Tool
  alsa-state.service                 loaded active running Manage Sound Card State (restore and store)
  atd.service                        loaded active running Job spooling tools
  auditd.service                     loaded active running Security Auditing Service
  avahi-daemon.service               loaded active running Avahi mDNS/DNS-SD Stack
  blk-availability.service           loaded active exited  Availability of block devices
  chronyd.service                    loaded active running NTP client/server
  crond.service                      loaded active running Command Scheduler
  cups.service                       loaded active running CUPS Printing Service
  dbus.service                       loaded active running D-Bus System Message Bus
  firewalld.service                  loaded active running firewalld - dynamic firewall daemon
  getty@tty1.service                 loaded active running Getty on tty1
  gssproxy.service                   loaded active running GSSAPI Proxy Daemon
  irqbalance.service                 loaded active running irqbalance daemon
  iscsi-shutdown.service             loaded active exited  Logout off all iSCSI sessions on shutdown
● kdump.service                      loaded failed failed  Crash recovery kernel arming
lines 1-20
  • 让服务开机启动
    systemctl enable crond.service
[root@linux7-128 ~]# systemctl enable crond.service 
[root@linux7-128 ~]# systemctl enable crond

可以不加.service

  • 不让开机启动
    systemctl disable crond
[root@linux7-128 ~]# systemctl disable crond 
Removed symlink /etc/systemd/system/multi-user.target.wants/crond.service.
  • 查看状态
    systemctl status crond
[root@linux7-128 ~]# systemctl status crond
● crond.service - Command Scheduler
   Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled; vendor preset: enabled)
   Active: active (running) since 二 2018-06-12 18:27:56 CST; 4h 20min ago
 Main PID: 939 (crond)
   CGroup: /system.slice/crond.service
           └─939 /usr/sbin/crond -n

6月 12 18:27:56 linux7-128 systemd[1]: Started Command Scheduler.
6月 12 18:27:56 linux7-128 systemd[1]: Starting Command Scheduler...
6月 12 18:27:56 linux7-128 crond[939]: (CRON) INFO (RANDOM_DELAY will be scaled with factor 38% if used.)
6月 12 18:27:56 linux7-128 crond[939]: (CRON) INFO (running with inotify support)
  • 停止服务
    systemctl stop crond
  • 启动服务
    systemctl start crond
  • 重启服务
    systemctl restart crond
  • 检查服务是否开机启动
    systemctl is-enabled crond
[root@linux7-128 ~]# systemctl is-enabled crond 
enabled
  • 根据输出信息获得service的配置文件内容
[root@linux7-128 ~]# systemctl enable crond
Created symlink from /etc/systemd/system/multi-user.target.wants/crond.service to /usr/lib/systemd/system/crond.service.
[root@linux7-128 ~]# cat /etc/systemd/system/multi-user.target.wants/crond.service
[Unit]
Description=Command Scheduler
After=auditd.service systemd-user-sessions.service time-sync.target

[Service]
EnvironmentFile=/etc/sysconfig/crond
ExecStart=/usr/sbin/crond -n $CRONDARGS
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process

[Install]
WantedBy=multi-user.target

[root@linux7-128 ~]# ls -l /etc/systemd/system/multi-user.target.wants/crond.service
lrwxrwxrwx 1 root root 37 6月  12 23:01 /etc/systemd/system/multi-user.target.wants/crond.service -> /usr/lib/systemd/system/crond.service

可以看到这是一个软链接,真正的文件路径是在/usr/lib/systemd/system/crond.service

[root@linux7-128 ~]# ls -l /usr/lib/systemd/system/crond.service
-rw-r--r--. 1 root root 284 8月   3 2017 /usr/lib/systemd/system/crond.service

如果enable开机启动就会生成一个软链接,如果disable不让开机启动,就会把软链接挪走

[root@linux7-128 ~]# systemctl disable crond 
Removed symlink /etc/systemd/system/multi-user.target.wants/crond.service.
[root@linux7-128 ~]# ls -l /etc/systemd/system/multi-user.target.wants/crond.service
ls: 无法访问/etc/systemd/system/multi-user.target.wants/crond.service: 没有那个文件或目录

unit介绍

  • 系统的unti所在目录
    /usr/lib/systemd/system
[root@linux7-128 ~]#  ls /usr/lib/systemd/system 
abrt-ccpp.service                        plymouth-kexec.service
abrtd.service                            plymouth-poweroff.service
abrt-oops.service                        plymouth-quit.service
abrt-pstoreoops.service                  plymouth-quit-wait.service
abrt-vmcore.service                      plymouth-read-write.service
abrt-xorg.service                        plymouth-reboot.service
accounts-daemon.service                  plymouth-start.service
alsa-restore.service                     plymouth-switch-root.service
alsa-state.service                       polkit.service
alsa-store.service                       postfix.service
anaconda-direct.service                  poweroff.target
anaconda-nm-config.service               poweroff.target.wants
anaconda-noshell.service                 printer.target
anaconda-pre.service                     proc-fs-nfsd.mount
anaconda.service                         proc-sys-fs-binfmt_misc.automount
anaconda-shell@.service                  proc-sys-fs-binfmt_misc.mount
anaconda-sshd.service                    psacct.service
...............

这些文件都叫unit

  • unit类型
service 系统服务 
 target 多个unit组成的组
 device 硬件设备
 mount 文件系统挂载点
 automount 自动挂载点
 path 文件或路径
 scope 不是由systemd启动的外部进程
 slice 进程组
 snapshot systemd快照
 socket 进程间通信套接字
 swap  swap文件
 timer 定时器

centos7也有类似和centos6相比较的系统级别

[root@linux7-128 ~]# cd !$
cd /usr/lib/systemd/system
[root@linux7-128 system]# ls -l runlevel*
lrwxrwxrwx. 1 root root 15 4月  27 20:58 runlevel0.target -> poweroff.target
lrwxrwxrwx. 1 root root 13 4月  27 20:58 runlevel1.target -> rescue.target
lrwxrwxrwx. 1 root root 17 4月  27 20:58 runlevel2.target -> multi-user.target
lrwxrwxrwx. 1 root root 17 4月  27 20:58 runlevel3.target -> multi-user.target
lrwxrwxrwx. 1 root root 17 4月  27 20:58 runlevel4.target -> multi-user.target
lrwxrwxrwx. 1 root root 16 4月  27 20:58 runlevel5.target -> graphical.target
lrwxrwxrwx. 1 root root 13 4月  27 20:58 runlevel6.target -> reboot.target

runlevel1.target.wants:
总用量 0
lrwxrwxrwx. 1 root root 39 4月  27 20:58 systemd-update-utmp-runlevel.service -> ../systemd-update-utmp-runlevel.service

runlevel2.target.wants:
总用量 0
lrwxrwxrwx. 1 root root 39 4月  27 20:58 systemd-update-utmp-runlevel.service -> ../systemd-update-utmp-runlevel.service

runlevel3.target.wants:
总用量 0
lrwxrwxrwx. 1 root root 39 4月  27 20:58 systemd-update-utmp-runlevel.service -> ../systemd-update-utmp-runlevel.service

runlevel4.target.wants:
总用量 0
lrwxrwxrwx. 1 root root 39 4月  27 20:58 systemd-update-utmp-runlevel.service -> ../systemd-update-utmp-runlevel.service

runlevel5.target.wants:
总用量 0
lrwxrwxrwx. 1 root root 39 4月  27 20:58 systemd-update-utmp-runlevel.service -> ../systemd-update-utmp-runlevel.service

同样也有7个级别的target,每个target对应软链接,源指的是后面的target

unit相关命令

  • 列出正在运行的unit
    systemctl list-units
[root@linux7-128 system]# systemctl list-units 
  UNIT                                            LOAD   ACTIVE SUB       DESCRIPTION
  proc-sys-fs-binfmt_misc.automount               loaded active waiting   Arbitrary Executable File Formats File System A
  sys-devices-pci0000:00-0000:00:07.1-ata2-host1-target1:0:0-1:0:0:0-block-sr0.device loaded active plugged   VMware_Virt
  sys-devices-pci0000:00-0000:00:10.0-host2-target2:0:0-2:0:0:0-block-sda-sda1.device loaded active plugged   VMware_Virt
  sys-devices-pci0000:00-0000:00:10.0-host2-target2:0:0-2:0:0:0-block-sda-sda2.device loaded active plugged   VMware_Virt
  sys-devices-pci0000:00-0000:00:10.0-host2-target2:0:0-2:0:0:0-block-sda-sda3.device loaded active plugged   VMware_Virt
  sys-devices-pci0000:00-0000:00:10.0-host2-target2:0:0-2:0:0:0-block-sda.device loaded active plugged   VMware_Virtual_S
  sys-devices-pci0000:00-0000:00:10.0-host2-target2:0:1-2:0:1:0-block-sdb-sdb1.device loaded active plugged   LVM PV Dd1J
  sys-devices-pci0000:00-0000:00:10.0-host2-target2:0:1-2:0:1:0-block-sdb-sdb2.device loaded active plugged   LVM PV x2pF
  sys-devices-pci0000:00-0000:00:10.0-host2-target2:0:1-2:0:1:0-block-sdb-sdb3.device loaded active plugged   LVM PV pmaL
  sys-devices-pci0000:00-0000:00:10.0-host2-target2:0:1-2:0:1:0-block-sdb.device loaded active plugged   VMware_Virtual_S
  sys-devices-pci0000:00-0000:00:11.0-0000:02:01.0-net-ens33.device loaded active plugged   82545EM Gigabit Ethernet Cont
  sys-devices-pci0000:00-0000:00:11.0-0000:02:02.0-sound-card0.device loaded active plugged   ES1371/ES1373 / Creative La
......................
......................

LOAD   = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB    = The low-level unit activation state, values depend on unit type.

143 loaded units listed. Pass --all to see loaded but inactive units, too.
To show all installed unit files use 'systemctl list-unit-files'.
lines 132-151/151 (END)
  • 如果要列出全部的unit,包括失败的或者inactive的,加–all
    systemctl list-units --all
  • 列出inactive的unit
    systemctl list-units --all --state=inactive
[root@linux7-128 system]# systemctl list-units --all --state=inactive 
  UNIT                                             LOAD      ACTIVE   SUB  DESCRIPTION
  proc-sys-fs-binfmt_misc.mount                    loaded    inactive dead Arbitrary Executable File Formats File System
  sys-fs-fuse-connections.mount                    loaded    inactive dead FUSE Control File System
  tmp.mount                                        loaded    inactive dead Temporary Directory
  systemd-ask-password-console.path                loaded    inactive dead Dispatch Password Requests to Console Director
  abrt-vmcore.service                              loaded    inactive dead Harvest vmcores for ABRT
  accounts-daemon.service                          loaded    inactive dead Accounts Service
  alsa-restore.service                             loaded    inactive dead Save/Restore Sound Card State
● apparmor.service                                 not-found inactive dead apparmor.service
  auth-rpcgss-module.service                       loaded    inactive dead Kernel Module supporting RPCSEC_GSS
  brandbot.service                                 loaded    inactive dead Flexible Branding Service
  cpupower.service                                 loaded    inactive dead Configure CPU power related settings
  dm-event.service                                 loaded    inactive dead Device-mapper event daemon

................
................
  • 列出状态为active的service
    systemctl list-units --type=service
[root@linux7-128 system]#  systemctl list-units --type=service
  UNIT                               LOAD   ACTIVE SUB     DESCRIPTION
  abrt-ccpp.service                  loaded active exited  Install ABRT coredump hook
  abrt-oops.service                  loaded active running ABRT kernel log watcher
  abrt-xorg.service                  loaded active running ABRT Xorg log watcher
  abrtd.service                      loaded active running ABRT Automated Bug Reporting Tool
  alsa-state.service                 loaded active running Manage Sound Card State (restore and store)
  atd.service                        loaded active running Job spooling tools
  auditd.service                     loaded active running Security Auditing Service
  avahi-daemon.service               loaded active running Avahi mDNS/DNS-SD Stack
  blk-availability.service           loaded active exited  Availability of block devices
  chronyd.service                    loaded active running NTP client/server
  crond.service                      loaded active running Command Scheduler
  cups.service                       loaded active running CUPS Printing Service
  dbus.service                       loaded active running D-Bus System Message Bus
  firewalld.service                  loaded active running firewalld - dynamic firewall daemon
  getty@tty1.service                 loaded active running Getty on tty1
  gssproxy.service                   loaded active running GSSAPI Proxy Daemon
  irqbalance.service                 loaded active running irqbalance daemon

...............
..............

不加–all会列出状态为active的service

  • 查看某个服务是否为active
    systemctl is-active crond.service
    也可以查看某个服务是否为enable
    systemctl is-enabled crond.service
[root@linux7-128 system]#  systemctl is-active crond.service 
active
[root@linux7-128 system]#  systemctl is-enabled crond.service 
enabled

target介绍

系统为了方便管理用target来管理unit

  • 列出系统里所有的target
    systemctl list-unit-files --type=target
[root@linux7-128 ~]#  systemctl list-unit-files --type=target
UNIT FILE                  STATE   
anaconda.target            static  
basic.target               static  
bluetooth.target           static  
cryptsetup-pre.target      static  
cryptsetup.target          static  
ctrl-alt-del.target        disabled
default.target             enabled 
emergency.target           static  
final.target               static  
getty.target               static  
graphical.target           static  
halt.target                disabled
hibernate.target           static  
hybrid-sleep.target        static  
initrd-fs.target           static  
initrd-root-fs.target      static  
initrd-switch-root.target  static  
initrd.target              static  
.................
  • 查看指定target下面有哪些unit
    systemctl list-dependencies multi-user.target
[root@linux7-128 ~]# systemctl list-dependencies multi-user.target 
multi-user.target
● ├─abrt-ccpp.service
● ├─abrt-oops.service
● ├─abrt-vmcore.service
● ├─abrt-xorg.service
● ├─abrtd.service
● ├─atd.service
● ├─auditd.service
● ├─avahi-daemon.service
● ├─brandbot.path
● ├─chronyd.service
● ├─crond.service
● ├─cups.path
● ├─cups.service
● ├─dbus.service
● ├─firewalld.service
● ├─irqbalance.service
● ├─kdump.service
● ├─ksm.service
● ├─ksmtuned.service
.............
  • 查看系统默认的target
    systemctl get-default
[root@linux7-128 ~]# systemctl get-default 
multi-user.target

centos7可以更改系统默认的target来达到类似centos6更改系统运行级别的效果

  • 设置默认的target
    systemctl set-default multi-user.target
[root@linux7-128 ~]# systemctl set-default multi-user.target
Removed symlink /etc/systemd/system/default.target.
Created symlink from /etc/systemd/system/default.target to /usr/lib/systemd/system/multi-user.target.
[root@linux7-128 ~]# ls -l /etc/systemd/system/default.target
lrwxrwxrwx 1 root root 41 6月  13 13:39 /etc/systemd/system/default.target -> /usr/lib/systemd/system/multi-user.target

设置的时候会创建一个软链接

  • 一个service属于一种类型的unit
    多个unit组成了一个target
    一个target里面包含了多个service

cat /usr/lib/systemd/system/sshd.service //看[install]部分

[root@linux7-128 ~]# cat /usr/lib/systemd/system/sshd.service
[Unit]
Description=OpenSSH server daemon
Documentation=man:sshd(8) man:sshd_config(5)
After=network.target sshd-keygen.service
Wants=sshd-keygen.service

[Service]
Type=notify
EnvironmentFile=/etc/sysconfig/sshd
ExecStart=/usr/sbin/sshd -D $OPTIONS
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
RestartSec=42s

[Install]
WantedBy=multi-user.target

**
总结:
系统由多种unit组成,为了方便管理归类成若干个类,每一类叫target。也就是说target由多个unit组成,service属于一种类型的unit,一个target里面有若干个service。**