第六周

总结

A–net1–1 R1 2–net2C–3 R2 4–net3D–5 R3 6–net4–B
R1
route add -net net4/N4  gw ip3  只加此条
route add -net net3/N3  gw ip3  不加
或者
route add default   gw ip3
R2
route add -net net1/N1  gw ip2
route add -net net4/N4  gw ip5
R3
route add -net net1/N1  gw ip4
route add -net net2/N2  gw ip4如果只是A和B通可以不加此条路由。
或者
route add default   gw ip4
查看DNS生没生效
cat /etc/resolv.conf
修改主机名:
[root@centos ~]#vim /etc/sysconfig/network
NETWORKING=yes
HOSTNAME=centos.localdomain
修改完成后不会立即生效
[root@centos ~]#hostname centos6.localdomain (新的主机名)
[root@centos ~]#hostname
centos6.localdomain
提示符没改退出一下就改了。
在这个文件里也可以加网关,需要重启才能生效,如果网卡里也有网关且和这个文件的网关不同,那么网卡里的网关生效。
也可以将旧的路由表删除,在路由表里添加进新的网关。
[root@centos ~]#vim /etc/sysconfig/network
NETWORKING=yes
HOSTNAME=centos.localdomain
GATEWAY=172.20.0.1
在主机有多个网卡时加路由表的时候只加一个默认路由,如果有2个默认路由可能会使自己上不去网。
[root@centos6 network-scripts]#route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.30.0    0.0.0.0         255.255.255.0   U     0      0        0 eth0
169.254.0.0     0.0.0.0         255.255.0.0     U     1002   0        0 eth0
169.254.0.0     0.0.0.0         255.255.0.0     U     1003   0        0 eth1
172.20.0.0      0.0.0.0         255.255.0.0     U     0      0        0 eth1
0.0.0.0         172.20.0.1      0.0.0.0         UG    0      0        0 eth1
如何在一个网卡上配置多个IP地址
[root@centos6 network-scripts]#ifconfig eth0:1 2.2.2.2/24    eth0是物理网卡,eth0:1 相当于给物理网卡起个别名
[root@centos6 network-scripts]#ifconfig     添加IP是临时的重启会丢失
eth0      Link encap:Ethernet  HWaddr 00:0C:29:6B:0D:B3
          inet addr:192.168.30.102  Bcast:192.168.30.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fe6b:db3/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:2201 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1824 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:199758 (195.0 KiB)  TX bytes:166640 (162.7 KiB)
eth0:1    Link encap:Ethernet  HWaddr 00:0C:29:6B:0D:B3
          inet addr:2.2.2.2  Bcast:2.2.2.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
在centos7上也加上同网段的地址,可以ping同
[root@CENTOS7 ~]#ifconfig ens33:1 2.2.2.100
[root@CENTOS7 ~]#ifconfig
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.30.101  netmask 255.255.255.0  broadcast 192.168.30.255
        inet6 fe80::19e7:a41a:a0ac:2f54  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:45:bf:14  txqueuelen 1000  (Ethernet)
        RX packets 1736  bytes 168092 (164.1 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 1589  bytes 127630 (124.6 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
ens33:1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 2.2.2.100  netmask 255.0.0.0  broadcast 2.255.255.255
        ether 00:0c:29:45:bf:14  txqueuelen 1000  (Ethernet)
[root@CENTOS7 ~]#ping 2.2.2.2
PING 2.2.2.2 (2.2.2.2) 56(84) bytes of data.
64 bytes from 2.2.2.2: icmp_seq=1 ttl=64 time=0.518 ms
64 bytes from 2.2.2.2: icmp_seq=2 ttl=64 time=0.976 ms
重启会删除eth0:1,
ifconfig eht0:1 down 也能删除eth0:1
想重启不丢失就要修改配置文件
[root@centos6 network-scripts]#cat > ifcfg-eth0:1
DEVICE=eth0:1
BOOTPROTO=none
IPADDR=3.3.3.3
PREFIX=24
添加完配置文件后需要关闭NetworkManager,否则有冲突
[root@centos6 network-scripts]#service NetworkManager stop
Stopping NetworkManager daemon:                            [  OK  ]
重新启动网络服务
[root@centos6 network-scripts]#service network restart
fgrep: ifcfg-ifcfg-: No such file or directory
fgrep: ifcfg-ifcfg-: No such file or directory
Shutting down interface eth0:                              [  OK  ]
Shutting down interface eth1:                              [  OK  ]
/etc/init.d/network: line 217: ./ifcfg-ifcfg-: No such file or directory
Shutting down loopback interface:                          [  OK  ]
Bringing up loopback interface:                            [  OK  ]
Bringing up interface eth0:  Determining if ip address 192.168.30.102 is already in use for device eth0…
Determining if ip address 3.3.3.3 is already in use for device eth0…
SIOCADDRT: Network is unreachable
                                                           [  OK  ]
Bringing up interface eth1:  Determining if ip address 172.20.68.100 is already in use for device eth1…
                                                           [  OK  ]
[root@centos6 network-scripts]#ifconfig
eth0      Link encap:Ethernet  HWaddr 00:0C:29:6B:0D:B3
          inet addr:192.168.30.102  Bcast:192.168.30.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fe6b:db3/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:2835 errors:0 dropped:0 overruns:0 frame:0
          TX packets:2253 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:255849 (249.8 KiB)  TX bytes:220130 (214.9 KiB)
eth0:1    Link encap:Ethernet  HWaddr 00:0C:29:6B:0D:B3
          inet addr:3.3.3.3  Bcast:3.3.3.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
eth1      Link encap:Ethernet  HWaddr 00:0C:29:6B:0D:BD
          inet addr:172.20.68.100  Bcast:172.20.255.255  Mask:255.255.0.0
教室楼上就是用这种方法配置的172.20.0.1和172.18.0.1
单臂路由的实现
ifconfig eth0:1 1.1.1.254/24
ifconfig eth0:2 2.2.2.254/24
echo 1 > /proc/sys/net/ipv4/ip_forward
A机器
ifconfig eth0 1.1.1.1/24
route add default gw 1.1.1.254
B机器
ifconfig eth0 2.2.2.2/24
route add default gw 2.2.2.254
ping 通后发现路由个数是64,LINUX默认穿过路由器才减一由于单臂路由没有穿过路由所以还是64
当ping一个网卡路由没有的地址时默认用物理网卡去ping
如果非要用别名网卡去ping,命令是
ping -I 3.3.3.3 1.1.1.254
tcpdump icmp -nn
netstat命令
?netstat – Print network connections, routing tables, interface statistics, masquerade
connections, and multicast memberships
?显示网络连接:
netstat [–tcp|-t] [–udp|-u] [–raw|-w] [–listening|-l] [–all|-a] [–
numeric|-n] [–extend|-e[–extend|-e]] [–program|-p]
-t: tcp协议相关
-u: udp协议相关
-w: raw socket相关
-l: 处于监听状态
-a: 所有状态
-n: 以数字显示IP和端口;
-e:扩展格式
-p: 显示相关进程及PID
netstat命令
?常用组合:
-tan, -uan, -tnl, -unl
?显示路由表:
netstat {–route|-r} [–numeric|-n]
-r: 显示内核路由表
-n: 数字格式
?显示接口统计数据:
netstat {–interfaces|-I|-i} [iface] [–all|-a] [–extend|-e] [–program|-p]
[–numeric|-n]
netstat -i
netstat –I=IFACE
ifconfig -s eth0
[root@centos6 network-scripts]#netstat -nr
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
192.168.30.0    0.0.0.0         255.255.255.0   U         0 0          0 eth0
3.3.3.0         0.0.0.0         255.255.255.0   U         0 0          0 eth0
169.254.0.0     0.0.0.0         255.255.0.0     U         0 0          0 eth0
169.254.0.0     0.0.0.0         255.255.0.0     U         0 0          0 eth1
172.20.0.0      0.0.0.0         255.255.0.0     U         0 0          0 eth1
0.0.0.0         172.20.0.1      0.0.0.0         UG        0 0          0 eth1
netstat -n   查看所有连接,本地的socket连接,tcp和udp等连接
socket文件  s开头的粉色文件 用于实现本地通讯,同一电脑上两个网络软件(A和B)通讯传给A将数据传给socket,再由socket传给B,省略封装解封装的过程
[root@centos6 ~]#ll /var/run/dbus/system_bus_socket
srwxrwxrwx. 1 root root 0 May  2 08:50 /var/run/dbus/system_bus_socket
[root@centos6 ~]#netstat -nt     显示的是正在连接的
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
tcp        0     64 192.168.30.102:22           192.168.30.1:55486          ESTABLISHED
[root@centos6 ~]#netstat -nutl     正在监听的UDP 和 TCP
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
tcp        0      0 0.0.0.0:58406               0.0.0.0:*                   LISTEN
tcp        0      0 0.0.0.0:111                 0.0.0.0:*                   LISTEN
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN
tcp        0      0 127.0.0.1:631               0.0.0.0:*                   LISTEN
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN
tcp        0      0 :::111                      :::*                        LISTEN
tcp        0      0 :::22                       :::*                        LISTEN
tcp        0      0 ::1:631                     :::*                        LISTEN
tcp        0      0 :::46232                    :::*                        LISTEN
tcp        0      0 ::1:25                      :::*                        LISTEN
udp        0      0 0.0.0.0:747                 0.0.0.0:*
udp        0      0 0.0.0.0:111                 0.0.0.0:*
udp        0      0 0.0.0.0:631                 0.0.0.0:*
udp        0      0 0.0.0.0:52228               0.0.0.0:*
udp        0      0 127.0.0.1:807               0.0.0.0:*
udp        0      0 :::747                      :::*
udp        0      0 :::111                      :::*
udp        0      0 :::54811                    :::*
[root@centos6 ~]#netstat -nuta       监听的和正在连接的统统都显示
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address               Foreign Address             State
tcp        0      0 0.0.0.0:58406               0.0.0.0:*                   LISTEN
tcp        0      0 0.0.0.0:111                 0.0.0.0:*                   LISTEN
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN
tcp        0      0 127.0.0.1:631               0.0.0.0:*                   LISTEN
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN
tcp        0    208 192.168.30.102:22           192.168.30.1:55486          ESTABLISHED
tcp        0      0 :::111                      :::*                        LISTEN
tcp        0      0 :::22                       :::*                        LISTEN
tcp        0      0 ::1:631                     :::*                        LISTEN
tcp        0      0 :::46232                    :::*                        LISTEN
tcp        0      0 ::1:25                      :::*                        LISTEN
udp        0      0 0.0.0.0:747                 0.0.0.0:*
udp        0      0 0.0.0.0:111                 0.0.0.0:*
udp        0      0 0.0.0.0:631                 0.0.0.0:*
udp        0      0 0.0.0.0:52228               0.0.0.0:*
udp        0      0 127.0.0.1:807               0.0.0.0:*
udp        0      0 :::747                      :::*
udp        0      0 :::111                      :::*
udp        0      0 :::54811                    :::*
[root@centos6 ~]#netstat -nutap           -p显示谁在使用这个连接
tcp        0      0 192.168.30.102:22           192.168.30.1:55486          ESTABLISHED 5182/sshd
[root@centos6 ~]#netstat -nutape        -e   显示扩展信息
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       User       Inode      PID/Program name
tcp        0      0 0.0.0.0:58406               0.0.0.0:*                   LISTEN      29         16478      2327/rpc.statd
tcp        0      0 0.0.0.0:111                 0.0.0.0:*                   LISTEN      0          16229      2268/rpcbind
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      0          17721
[root@centos6 network-scripts]#netstat -i
Kernel Interface table
Iface       MTU Met    RX-OK RX-ERR RX-DRP RX-OVR    TX-OK TX-ERR TX-DRP TX-OVR Flg
eth0       1500   0     4105      0      0      0     3166      0      0      0 BMRU
lo        65536   0       12      0      0      0       12      0      0      0 LRU
[root@centos6 network-scripts]#netstat -Ieth0         -i  显示网卡端口信息
Kernel Interface table
Iface       MTU Met    RX-OK RX-ERR RX-DRP RX-OVR    TX-OK TX-ERR TX-DRP TX-OVR Flg
eth0       1500   0     4148      0      0      0     3195      0      0      0 BMRU
[root@centos6 network-scripts]#ifconfig -s eth0
Iface   MTU Met    RX-OK RX-ERR RX-DRP RX-OVR    TX-OK TX-ERR TX-DRP TX-OVR Flg
eth0       1500   0     4243      0      0      0     3257      0      0      0 BMRU
RX-OK 正常的包
RX-ERR错误的包
RX-DRP扔掉的包
RX-OVR过载的包
[root@centos6 network-scripts]#ss -nutlap
Netid  State      Recv-Q Send-Q                   Local Address:Port                     Peer Address:Port
udp    UNCONN     0      0                                    *:747                                 *:*      users:((“rpcbind”,2268,7))
udp    UNCONN     0      0                                    *:111                                 *:*      users:((“rpcbind”,2268,6))
udp    UNCONN     0      0                                    *:631                                 *:*      users:((“cupsd”,2372,9))
udp    UNCONN     0      0                                    *:52228                               *:*      users:((“rpc.statd”,2327,8))
udp    UNCONN     0      0                            127.0.0.1:807                                 *:*      users:((“rpc.statd”,2327,5))
udp    UNCONN     0      0                                   :::747                                :::*
ss命令
?格式:ss [OPTION]… [FILTER]
? netstat通过遍历proc来获取socket信息,ss使用netlink与内核tcp_diag模块通信获取socket信
息。
?选项:
-t: tcp协议相关
-u: udp协议相关
-w: 裸套接字相关
-x:unix sock相关
-l: listen状态的连接
-a: 所有
-n: 数字格式
-p: 相关的程序及PID
-e: 扩展的信息
-m:内存用量
-o:计时器信息
ss命令
? FILTER : [ state TCP-STATE ] [ EXPRESSION ]
? TCP的常见状态:
tcp finite state machine:
LISTEN: 监听
ESTABLISHED:已建立的连接
FIN_WAIT_1
FIN_WAIT_2
SYN_SENT
SYN_RECV
CLOSED
? EXPRESSION:
dport =
sport =
示例:’( dport = :ssh or sport = :ssh )’
? 常用组合:
-tan, -tanl, -tanlp, -uan
常见用法
?ss -l 显示本地打开的所有端口
?ss -pl 显示每个进程具体打开的socket
?ss -t -a 显示所有tcp socket
?ss -u -a 显示所有的UDP Socekt
?ss -o state established ‘( dport = :ssh or sport = :ssh )’ 显示所有已建立的
ssh连接
?ss -o state established ‘( dport = :http or sport = :http )’ 显示所有已建立
的HTTP连接
?ss -s 列出当前socket详细信息
[root@centos6 network-scripts]#ss -o state established ‘( dport = :ssh or sport = :ssh )’
Recv-Q Send-Q                                      Local Address:Port                                          Peer Address:Port
0      64                                         192.168.30.102:ssh                                           192.168.30.1:55486    timer:(on,220ms,0)
ip命令:
?配置Linux网络属性:ip命令
?ip – show / manipulate routing, devices, policy routing and tunnels
ip [ OPTIONS ] OBJECT { COMMAND | help }
OBJECT := { link | addr | route }
ip link – network device configuration
set dev IFACE
可设置属性:
up and down:激活或禁用指定接口
ifup/ifdown
show [dev IFACE]:指定接口
[up]:仅显示处于激活状态的接口
ip命令
? ip addr { add | del } IFADDR dev STRING
[label LABEL]:添加地址时指明网卡别名
[scope {global|link|host}]:指明作用域
global: 全局可用
link: 仅链接可用
host: 本机可用
[broadcast ADDRESS]:指明广播地址
? ip address show – look at protocol addresses
[dev DEVICE]
[label PATTERN]
[primary and secondary]
? ip address flush – 使用格式同show
ip addr add 172.16.100.100/16 dev eth0 label eth0:0
ip addr del 172.16.100.100/16 dev eth0 label eth0:0
ip addr flush dev eth0 label eth0:0
ip命令
? ip route – routing table management
添加路由:ip route add
ip route add TARGET via GW dev IFACE src SOURCE_IP
TARGET:
主机路由:IP
网络路由:NETWORK/MASK
ip route add 192.168.0.0/24 via 172.16.0.1
ip route add 192.168.1.13 via 172.16.0.1
添加网关:ip route add default via GW dev IFACE
ip route add default via 172.16.0.1
删除路由:ip route delete
ip route del TARGET
显示路由:ip route show|list
清空路由表:ip route flush [dev IFACE]  [via PREFIX]
ip route flush dev eth0
[root@CENTOS7 ~]#ip r a 2.2.2.0/24 via 172.20.0.1 dev ens37
[root@CENTOS7 ~]#route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         172.20.0.1      0.0.0.0         UG    100    0        0 ens37
1.1.1.0         172.20.0.1      255.255.255.0   UG    0      0        0 ens37
2.2.2.0         172.20.0.1      255.255.255.0   UG    0      0        0 ens37
172.20.0.0      0.0.0.0         255.255.0.0     U     100    0        0 ens37
192.168.30.0    0.0.0.0         255.255.255.0   U     100    0        0 ens33
[root@CENTOS7 ~]#ip r
default via 172.20.0.1 dev ens37 proto static metric 100
1.1.1.0/24 via 172.20.0.1 dev ens37
2.2.2.0/24 via 172.20.0.1 dev ens37
172.20.0.0/16 dev ens37 proto kernel scope link src 172.20.109.255 metric 100
192.168.30.0/24 dev ens33 proto kernel scope link src 192.168.30.101 metric 100
[root@CENTOS7 ~]#ip r d 1.1.1.0/24 via 172.20.0.1 dev ens37
[root@CENTOS7 ~]#ip r d 2.2.2.0/24 via 172.20.0.1 dev ens37
[root@CENTOS7 ~]#route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         172.20.0.1      0.0.0.0         UG    100    0        0 ens37
172.20.0.0      0.0.0.0         255.255.0.0     U     100    0        0 ens37
192.168.30.0    0.0.0.0         255.255.255.0   U     100    0        0 ens33
[root@CENTOS7 ~]#ip a a 1.1.1.1/24 dev ens33
[root@CENTOS7 ~]#ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: ens33: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:45:bf:14 brd ff:ff:ff:ff:ff:ff
    inet 192.168.30.101/24 brd 192.168.30.255 scope global dynamic ens33
       valid_lft 1369sec preferred_lft 1369sec
    inet 1.1.1.1/24 scope global ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::19e7:a41a:a0ac:2f54/64 scope link
       valid_lft forever preferred_lft forever
3: ens37: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:45:bf:1e brd ff:ff:ff:ff:ff:ff
    inet 172.20.109.255/16 brd 172.20.255.255 scope global dynamic ens37
       valid_lft 83353sec preferred_lft 83353sec
    inet6 fe80::2ee4:100d:665:521f/64 scope link
       valid_lft forever preferred_lft forever
[root@CENTOS7 ~]#ifconfig
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.30.101  netmask 255.255.255.0  broadcast 192.168.30.255
        inet6 fe80::19e7:a41a:a0ac:2f54  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:45:bf:14  txqueuelen 1000  (Ethernet)
        RX packets 1497  bytes 138405 (135.1 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 1138  bytes 145694 (142.2 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
ens37: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.20.109.255  netmask 255.255.0.0  broadcast 172.20.255.255
        inet6 fe80::2ee4:100d:665:521f  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:45:bf:1e  txqueuelen 1000  (Ethernet)
        RX packets 270968  bytes 18935607 (18.0 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 214  bytes 30457 (29.7 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1  (Local Loopback)
        RX packets 12  bytes 1404 (1.3 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 12  bytes 1404 (1.3 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
[root@CENTOS7 ~]#ip a a 1.2.1.1/24 dev ens33 label ens33:1
[root@CENTOS7 ~]#ifconfig
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.30.101  netmask 255.255.255.0  broadcast 192.168.30.255
        inet6 fe80::19e7:a41a:a0ac:2f54  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:45:bf:14  txqueuelen 1000  (Ethernet)
        RX packets 1640  bytes 151663 (148.1 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 1240  bytes 158620 (154.9 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
ens33:1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 1.2.1.1  netmask 255.255.255.0  broadcast 0.0.0.0
        ether 00:0c:29:45:bf:14  txqueuelen 1000  (Ethernet)
ens37: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.20.109.255  netmask 255.255.0.0  broadcast 172.20.255.255
        inet6 fe80::2ee4:100d:665:521f  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:45:bf:1e  txqueuelen 1000  (Ethernet)
        RX packets 271326  bytes 18995299 (18.1 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 214  bytes 30457 (29.7 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1  (Local Loopback)
        RX packets 12  bytes 1404 (1.3 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 12  bytes 1404 (1.3 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
[root@centos6 ~]#ip link set eth1 down
[root@centos6 ~]#ifconfig
eth0      Link encap:Ethernet  HWaddr 00:0C:29:6B:0D:B3
          inet addr:192.168.30.102  Bcast:192.168.30.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fe6b:db3/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:2929 errors:0 dropped:0 overruns:0 frame:0
          TX packets:2155 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:253587 (247.6 KiB)  TX bytes:326762 (319.1 KiB)
lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:64 errors:0 dropped:0 overruns:0 frame:0
          TX packets:64 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:4936 (4.8 KiB)  TX bytes:4936 (4.8 KiB)
[root@centos6 ~]#ip l
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:6b:0d:b3 brd ff:ff:ff:ff:ff:ff
3: eth1: <BROADCAST,MULTICAST> mtu 1500 qdisc pfifo_fast state DOWN qlen 1000
    link/ether 00:0c:29:6b:0d:bd brd ff:ff:ff:ff:ff:ff
[root@centos6 ~]#ip link set eth1 up
[root@centos6 ~]#ip link
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:6b:0d:b3 brd ff:ff:ff:ff:ff:ff
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:6b:0d:bd brd ff:ff:ff:ff:ff:ff
grobal全局ip
本地网卡eth0
在centos6上
ip a a 1.1.1.1/24 dev eth0
ip a a 2.2.2.2/24 dev eth0
ip a a 3.3.3.3/24 dev eth0
ip a a 5.5.5.5/24 dev eth1
本地网卡ens33
ip a a 1.1.1.2/24 dev eth0
ip a d default via 172.20.0.1 dev ens37 proto static metric 100     删除路由表
ip a a default via 1.1.1.1 dev ens33
就能ping通所有centos6上的IP地址
global的地址在内核内,只要能到达任何一个网卡就把所有的globalip地址响应
link 只响应到达本网卡的ip地址
host 只能在本机有效
ip a flush dev eth0 清除eth0上的所有地址
网络配置文件
?IP、MASK、GW、DNS相关配置文件:/etc/sysconfig/network-
scripts/ifcfg-IFACE
?路由相关的配置文件:
/etc/sysconfig/network-scripts/route-IFACE
?/etc/sysconfig/network-scripts/ifcfg-IFACE:
说明参考/usr/share/doc/initscripts-9.49.30/sysconfig.txt
DEVICE:此配置文件应用到的设备
HWADDR:对应的设备的MAC地址
BOOTPROTO:激活此设备时使用的地址配置协议,常用的dhcp, static,
none, bootp
NM_CONTROLLED:NM是NetworkManager的简写,此网卡是否接受
NM控制;建议CentOS6为“no”
网络配置文件
?ONBOOT:在系统引导时是否激活此设备
?TYPE:接口类型;常见有的Ethernet, Bridge
?UUID:设备的惟一标识
?IPADDR:指明IP地址
?NETMASK:子网掩码
?GATEWAY: 默认网关
?DNS1:第一个DNS服务器指向
?DNS2:第二个DNS服务器指向
?USERCTL:普通用户是否可控制此设备     后面跟=yes或者=no,
?PEERDNS:如果BOOTPROTO的值为“dhcp”,是否允许dhcp server分配的
dns服务器指向信息直接覆盖至/etc/resolv.conf文件中
主机名和本地解析器
?配置当前主机的主机名:
hostname [HOSTNAME]
/etc/sysconfig/network
HOSTNAME=
?解析器执行正向和逆向查询
?/etc/hosts
? 本地主机名数据库和IP地址的映像
? 对小型独立网络有用
? 通常,在使用DNS前检查
? getent hosts 查看/etc/hosts 内容
dns名字解析
? /etc/resolv.conf
nameserver DNS_SERVER_IP1
nameserver DNS_SERVER_IP2
nameserver DNS_SERVER_IP3
search magedu.com
? /etc/nsswitch.conf
与/etc/hosts相比优先于DNS
? 正向解析:FQDN–>IP
dig -t A FQDN
host -t A FQDN
? 反向解析:IP–>FQDN
dig -x IP
host -t PTR IP
网络配置文件
?/etc/sysconfig/network-scripts/route-IFACE(跟网卡名)
? 注意:需service network restart生效
? 两种风格:
(1) TARGET via GW
如:10.0.0.0/8 via 172.16.0.1
(2) 每三行定义一条路由
ADDRESS#=TARGET
NETMASK#=mask
GATEWAY#=GW
永久增加路由表
[root@centos6 network-scripts]#vim route-eth1
6.6.6.0/24 via 172.20.0.1
重启网络服务
service network restart
[root@centos6 network-scripts]#route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.30.0    0.0.0.0         255.255.255.0   U     0      0        0 eth0
6.6.6.0         172.20.0.1      255.255.255.0   UG    0      0        0 eth1
169.254.0.0     0.0.0.0         255.255.0.0     U     1002   0        0 eth0
169.254.0.0     0.0.0.0         255.255.0.0     U     1003   0        0 eth1
172.20.0.0      0.0.0.0         255.255.0.0     U     0      0        0 eth1
0.0.0.0         172.20.0.1      0.0.0.0         UG    0      0        0 eth1
[root@centos6 ~]#ip r d 6.6.6.0/24 via 172.20.0.1 dev eth1
[root@centos6 ~]#route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.30.0    0.0.0.0         255.255.255.0   U     0      0        0 eth0
169.254.0.0     0.0.0.0         255.255.0.0     U     1002   0        0 eth0
169.254.0.0     0.0.0.0         255.255.0.0     U     1003   0        0 eth1
172.20.0.0      0.0.0.0         255.255.0.0     U     0      0        0 eth1
0.0.0.0         172.20.0.1      0.0.0.0         UG    0      0        0 eth1
一个网卡同时拥有dhcp 和 静态获取地址
[root@centos6 network-scripts]#cp ifcfg-eth1 ifcfg-eth1:2
[root@centos6 network-scripts]#vim ifcfg-eth1
DEVICE=eth1
BOOTPROTO=dhcp
IPADDR=172.20.68.100
PREFIX=16
GATEWAY=172.20.0.1
DNS1=114.114.114.114
DNS2=1.1.1.1
~
[root@centos6 network-scripts]#vim ifcfg-eth1:2
DEVICE=eth1:2
BOOTPROTO=none
IPADDR=172.20.68.100
PREFIX=16
GATEWAY=172.20.0.1
DNS1=114.114.114.114
DNS2=1.1.1.1
重启网络服务
[root@centos6 network-scripts]#ifconfig
eth0      Link encap:Ethernet  HWaddr 00:0C:29:6B:0D:B3
          inet addr:192.168.30.102  Bcast:192.168.30.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fe6b:db3/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:4500 errors:0 dropped:0 overruns:0 frame:0
          TX packets:3250 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:396030 (386.7 KiB)  TX bytes:484136 (472.7 KiB)
eth1      Link encap:Ethernet  HWaddr 00:0C:29:6B:0D:BD
          inet addr:172.20.102.175  Bcast:172.20.255.255  Mask:255.255.0.0
          inet6 addr: fe80::20c:29ff:fe6b:dbd/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:292549 errors:0 dropped:0 overruns:0 frame:0
          TX packets:6450 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:42801616 (40.8 MiB)  TX bytes:401543 (392.1 KiB)
eth1:2    Link encap:Ethernet  HWaddr 00:0C:29:6B:0D:BD
          inet addr:172.20.68.100  Bcast:172.20.255.255  Mask:255.255.0.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:64 errors:0 dropped:0 overruns:0 frame:0
          TX packets:64 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:4936 (4.8 KiB)  TX bytes:4936 (4.8 KiB)
在标准网卡里面可以自动获取也可以手工指定,在网卡别名里面只能手工指定不能自动获取。
[root@centos6 ~]#vim /etc/hosts    地址解析文件。
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
6.6.6.6 www.magedu.com
192.168.30.101 centos7
在这个文件中加入地址及其域名,访问该域名事就直接访问地址,不需要走DNS(地址解析器)
修改本机名后最好在hosts文件中加入本机名否则可能导致一些访问失败(这些访问只通过主机名获取ip地址)
默认的优先级是hosts文件的优先级高于dns
在文件cat /etc/nsswitch.conf
[root@centos6 ~]#cat /etc/nsswitch.conf
#
# /etc/nsswitch.conf
#
# An example Name Service Switch config file. This file should be
# sorted with the most-used services at the beginning.
#
# The entry ‘[NOTFOUND=return]’ means that the search for an
# entry should stop if the search in the previous entry turned
# up nothing. Note that if the search failed due to some other reason
# (like no NIS server responding) then the search continues with the
# next entry.
#
# Valid entries include:
#
# nisplus Use NIS+ (NIS version 3)
# nis Use NIS (NIS version 2), also called YP
# dns Use DNS (Domain Name Service)
# files Use the local files
# db Use the local database (.db) files
# compat Use NIS on compat mode
# hesiod Use Hesiod for user lookups
# [NOTFOUND=return] Stop searching if not found so far
#
# To use db, put the “db” in front of “files” for entries you want to be
# looked up first in the databases
#
# Example:
#passwd:    db files nisplus nis
#shadow:    db files nisplus nis
#group:     db files nisplus nis
passwd:     files
shadow:     files
group:      files
#hosts:     db files nisplus nis dns
hosts:      files dns
将files和dns调换位置后就dns的优先级高于hosts
[root@centos6 ~]#getent hosts
127.0.0.1       localhost localhost.localdomain localhost4 localhost4.localdomain4 centos6
127.0.0.1       localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.30.101  centos7
网卡别名
?对虚拟主机有用
?将多个IP地址绑定到一个NIC上
eth0:1 、eth0:2、eth0:3
?ifconfig命令:
ifconfig eth0:0 192.168.1.100/24 up
ifconfig eth0:0 down
?ip命令:
ip addr add 172.16.1.2/16 dev eth0
ip addr add 172.16.1.1/16 dev eth0 label eth0:0
ip addr add 172.16.1.2/16 dev eth0 label eth0:0
ip addr del 172.16.1.1/16 dev eth0 label eth0:0
ip addr flush dev eth0 label eth0:0
设备别名
?为每个设备别名生成独立的接口配置文件
? 关闭NetworkManager服务
? ifcfg-ethX:xxx
? 必须使用静态联网
DEVICE=eth0:0
IPADDR=10.10.10.10
NETMASK=255.0.0.0
ONPARENT=yes
?注意:service network restart 生效
?参考/usr/share/doc/initscripts-*/sysconfig.txt
网络接口配置-bonding
?Bonding
将多块网卡绑定同一IP地址对外提供服务,可以实现高可用或者负载均衡。直接给
两块网卡设置同一IP地址是不可以的。通过bonding,虚拟一块网卡对外提供连接,
物理网卡的被修改为相同的MAC地址
Bonding工作模式
?Mode 0 (balance-rr)
轮转(Round-robin)策略:从头到尾顺序的在每一个slave
接口上面发送数据包。本模式提供负载均衡和容错的能力
?Mode 1 (active-backup)
活动-备份(主备)策略:只有一个slave被激活,当且仅当活动的slave接口失
败时才会激活其他slave。为了避免交换机发生混乱此时绑定的MAC地址只有
一个外部端口上可见
?Mode 3 (broadcast)
广播策略:在所有的slave接口上传送所有的报文,提供容错能力
?active-backup、balance-tlb 和 balance-alb 模式不需要交换机的任何特
殊配置。其他绑定模式需要配置交换机以便整合链接。如:Cisco 交换机需
要在模式 0、2 和 3 中使用 EtherChannel,但在模式4中需要 LACP和
EtherChannel
Bonding配置
?创建bonding设备的配置文件
?/etc/sysconfig/network-scripts/ifcfg-bond0
DEVICE=bond0
BOOTPROTO=none
BONDING_OPTS= “miimon=100 mode=0”
?/etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
BOOTPROTO=none
MASTER=bond0
SLAVE=yes
USERCTL=no
?查看bond0状态:/proc/net/bonding/bond0
Bonding配置
?miimon 是用来进行链路监测的。如果miimon=100,那么系统每
100ms 监测一次链路连接状态,如果有一条线路不通就转入另一条线路
?删除bond0
ifconfig bond0 down
rmmod bonding
?详细帮助:
/usr/share/doc/kernel-doc-
version/Documentation/networking/bonding.txt
https://www.kernel.org/doc/Documentation/networking/bondi
ng.txt
实现bonding的网卡必须是同一个网段的两个网卡。
cdnet
rm -f ifcfg-eth*     删除所有的网卡的配置文件
cat > ifcfg-bond0    配置bond0
DEVICE=bond0
BOOTPROTO=none
IPADDR=192.168.30.101
PREFIX=24
BONDING_OPTS=”mode=1 miimon=100″
cat > ifcfg-eth0    配置bond0中的eth0
DEVICE=eth0
MASTER=bond0
SLAVE=YES
cat > ifcfg-eth1  配置bond0中的eth1
DEVICE=eth1
MASTER=bond0
SLAVE=YES
重启网络服务
cat /proc/net/bonding/bond0    查看谁是活动的网卡谁是备用的网卡
关闭eth0拔掉网线
ping 并不影响,但是会丢失几个数据包
cat /proc/net/bonding/bond0
发现现在活动网卡是eth1,自动替换了eth0
都拔掉网线ping不通了,随便恢复网卡任意一个都会继续再ping通。
DEVICE=bond0
BOOTPROTO=none
IPADDR=192.168.30.101
PREFIX=24
BONDING_OPTS=”mode=3 miimon=100″
cat > ifcfg-eth0    配置bond0中的eth0
DEVICE=eth0
MASTER=bond0
SLAVE=YES
cat > ifcfg-eth1  配置bond0中的eth1
DEVICE=eth1
MASTER=bond0
SLAVE=YES
ping 192.168.30.101 时会回复两个包。
删除bonding
首先禁用bonding
ifconfig bond0 down
卸载bonding 的驱动模块
lsmod 查看本机的所有驱动模块
modprobe -r bonding
删除 /etc/sysconfig/network-script/ifcfg-bond0
修改该目录下的eth0 和 eth1 使其恢复到默认。
从新启动网络服务
CentOS 7网络属性配置
? CentOS 6之前,网络接口使用连续号码命名:eth0、eth1等,当增加或删除网卡时,名
称可能会发生变化,导致配置文件发生错误。
? CentOS 7使用基于硬件,设备拓扑和设置类型命名:
? (1) 网卡命名机制
systemd对网络设备的命名方式
(a) 如果Firmware或BIOS为主板上集成的设备提供的索引信息可用,且可预测则
根据此索引进行命名,例如eno1
(b) 如果Firmware或BIOS为PCI-E扩展槽所提供的索引信息可用,且可预测,则根
据此索引进行命名,例如ens1
(c) 如果硬件接口的物理位置信息可用,则根据此信息进行命名,例如enp2s0
(d) 如果用户显式启动,也可根据MAC地址进行命名,enx2387a1dc56
(e) 上述均不可用时,则使用传统命名机制
网卡名称
?基于BIOS支持启用biosdevname软件
内置网卡:em1,em2
pci卡:pYpX Y:slot ,X:port
?(2) 名称组成格式
en: Ethernet 有线局域网
wl: wlan 无线局域网
ww: wwan无线广域网
名称类型:
o<index>: 集成设备的设备索引号
s<slot>: 扩展槽的索引号
x<MAC>: 基于MAC地址的命名
p<bus>s<slot>: enp2s1
采用传统命名方式
?使用传统命名方式:
?(1) 编辑/etc/default/grub配置文件
GRUB_CMDLINE_LINUX =”rhgb quiet net.ifnames=0″
或:修改/boot/grub2/grub.cfg
?(2) 为grub2生成其配置文件
grub2-mkconfig -o /etc/grub2.cfg
?(3) 重启系统
修改centos7的网卡名
[root@CENTOS7 ~]#vim /etc/default/grub
GRUB_TIMEOUT=5
GRUB_DISTRIBUTOR=”$(sed ‘s, release .*$,,g’ /etc/system-release)”
GRUB_DEFAULT=saved
GRUB_DISABLE_SUBMENU=true
GRUB_TERMINAL_OUTPUT=”console”
GRUB_CMDLINE_LINUX=”crashkernel=auto rhgb quiet net.ifnames=0″    在此行加入net.ifname=0
GRUB_DISABLE_RECOVERY=”true”
修改完文件没有生成相应配置
[root@CENTOS7 ~]#grub2-mkconfig -o /etc/grub2.cfg   生成相应配置
Generating grub configuration file …
Found linux image: /boot/vmlinuz-3.10.0-693.el7.x86_64
Found initrd image: /boot/initramfs-3.10.0-693.el7.x86_64.img
Found linux image: /boot/vmlinuz-0-rescue-d9b2c489cdf948f8b487e98005c15e1c
Found initrd image: /boot/initramfs-0-rescue-d9b2c489cdf948f8b487e98005c15e1c.img
done
也可以直接修改下面文件的最后一行添加 net.ifnames=0
[root@CENTOS7 ~]#vim /boot/grub2/grub.cfg
menuentry ‘CentOS Linux (3.10.0-693.el7.x86_64) 7 (Core)’ –class centos –class gnu-lin
ux –class gnu –class os –unrestricted $menuentry_id_option ‘gnulinux-3.10.0-693.el7.x
86_64-advanced-0a1bc23e-06e5-4210-9b32-0edbff09ca1a’ {
        load_video
        set gfxpayload=keep
        insmod gzio
        insmod part_msdos
        insmod xfs
        set root=’hd0,msdos1′
        if [ x$feature_platform_search_hint = xy ]; then
          search –no-floppy –fs-uuid –set=root –hint-bios=hd0,msdos1 –hint-efi=hd0,
msdos1 –hint-baremetal=ahci0,msdos1 –hint=’hd0,msdos1′  4d8d9214-eeed-4758-8c34-f05492
b9ea73
        else
          search –no-floppy –fs-uuid –set=root 4d8d9214-eeed-4758-8c34-f05492b9ea73
        fi
        linux16 /vmlinuz-3.10.0-693.el7.x86_64 root=UUID=0a1bc23e-06e5-4210-9b32-0edbff0
9ca1a ro crashkernel=auto rhgb quiet net.ifnames=0
CentOS 7网络配置工具
? CentOS7主机名
? 配置文件:/etc/hostname ,默认没有此文件,通过DNS反向解析获取主机名,主机名
默认为:localhost.localdomain
? 显示主机名信息
hostname
hostnamectl status
? 设置主机名
hostnamectl set-hostname centos7.magedu.com
? 删除文件/etc/hostname,恢复主机名localhost.localdomain
? CentOS 7网络配置工具
? 图形工具:nm-connection-editor
? 字符配置tui工具:nmtui
? 命令行工具:nmcli
nmcli命令
? 地址配置工具:nmcli
? nmcli [ OPTIONS ] OBJECT { COMMAND | help }
device – show and manage network interfaces
nmcli device help
connection – start, stop, and manage network connections
nmcli connection help
? 修改IP地址等属性:
nmcli connection modify IFACE [+|-]setting.property value
setting.property:
ipv4.addresses ipv4.gateway
ipv4.dns1 ipv4.method manual | auto
? 修改配置文件执行生效:systemctl restart network
nmcli con reload
? nmcli命令生效: nmcli con down eth0 ;nmcli con up eth0
使用nmcli配置网络
?NeworkManager是管理和监控网络设置的守护进程
?设备即网络接口,连接是对网络接口的配置。一个网络接口可有多个连接配置,
但同时只有一个连接配置生效
?显示所有包括不活动连接
nmcli con show
?显示所有活动连接
nmcli con show –active
?显示网络连接配置
nmcli con show “System eth0“
?显示设备状态
nmcli dev status
使用nmcli配置网络
显示网络接口属性
nmcli dev show eth0
?创建新连接default,IP自动通过dhcp获取
nmcli con add con-name default type Ethernet ifname eth0
?删除连接
nmcli con del default
?创建新连接static ,指定静态IP,不自动连接
nmcti con add con-name static ifname eth0 autoconnect no type
Ethernet ipv4.addresses 172.25.X.10/24 ipv4.gateway 172.25.X.254
使用nmcli配置网络
?启用static连接配置
nmcli con up static
?启用default连接配置
nmcli con up default
?查看帮助
nmcli con add help
使用nmcli配置网络
?修改连接设置
nmcli con mod“static” connection.autoconnect no
nmcli con mod “static” ipv4.dns 172.25.X.254
nmcli con mod “static” +ipv4.dns 8.8.8.8
nmcli con mod “static” -ipv4.dns 8.8.8.8
nmcli con mod “static” ipv4.addresses “172.25.X.10/24 172.25.X.254”
nmcli con mod “static” +ipv4.addresses 10.10.10.10/16
?DNS设置,存放在/etc/resolv.conf文件中
PEERDNS=no 表示当IP通过dhcp自动获取时,dns仍是手动设置,不自动获取。等价于下
面命令:
nmcli con mod “system eth0” ipv4.ignore-auto-dns yes
使用mncli 配置eth0和eth1:
删除原来的配置文件
[root@CENTOS7 network-scripts]#rm -f ifcfg-ens33
[root@CENTOS7 network-scripts]#nmcli device status       查看当前网卡的状态信息,  connection代表着一份配置文件
DEVICE  TYPE      STATE      CONNECTION
eth0    ethernet  connected  Wired connection 1
eth1    ethernet  connected  Wired connection 2
lo      loopback  unmanaged  —
[root@CENTOS7 network-scripts]#nmcli connection show
NAME                UUID                                  TYPE            DEVICE
Wired connection 1  33424e5b-2b3d-32bc-b8a8-ac48620fd6fe  802-3-ethernet  eth0
Wired connection 2  baceab37-6abd-3c3e-a886-5b1513017d6b  802-3-ethernet  eth1
ens33               15fdb949-5c4d-4c76-a17e-8e4491fb8cb4  802-3-ethernet  —
上面的配置文件放在内存中实际中并没有配置这两个网卡的文件
[root@CENTOS7 network-scripts]#ls
ifcfg-lo     ifdown-post      ifup-aliases  ifup-plusb     ifup-wireless
ifdown       ifdown-ppp       ifup-bnep     ifup-post      init.ipv6-global
ifdown-bnep  ifdown-routes    ifup-eth      ifup-ppp       network-functions
ifdown-eth   ifdown-sit       ifup-ib       ifup-routes    network-functions-ipv6
ifdown-ib    ifdown-Team      ifup-ippp     ifup-sit
ifdown-ippp  ifdown-TeamPort  ifup-ipv6     ifup-Team
ifdown-ipv6  ifdown-tunnel    ifup-isdn     ifup-TeamPort
ifdown-isdn  ifup             ifup-plip     ifup-tunnel
[root@CENTOS7 network-scripts]#nmcli connection delete ens33     删除ens33这个配置文件
Connection ‘ens33’ (15fdb949-5c4d-4c76-a17e-8e4491fb8cb4) successfully deleted.
用nmcli配置eth1的配置文件:
[root@CENTOS7 network-scripts]#nmcli connection add con-name eth1 ifname eth1 type ethernet ipv4.method auto connection.autoconnect yes
Connection ‘eth1’ (e5e67bba-e114-4426-ba5f-59e58f0adeed) successfully added.
[root@CENTOS7 network-scripts]#nmcli connection show
NAME                UUID                                  TYPE            DEVICE
Wired connection 1  33424e5b-2b3d-32bc-b8a8-ac48620fd6fe  802-3-ethernet  eth0
Wired connection 2  baceab37-6abd-3c3e-a886-5b1513017d6b  802-3-ethernet  eth1
eth1                e5e67bba-e114-4426-ba5f-59e58f0adeed  802-3-ethernet  —       没有生效
生效命令是
[root@CENTOS7 network-scripts]#nmcli connection up eth1
Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/3)
[root@CENTOS7 network-scripts]#nmcli connection show
NAME                UUID                                  TYPE            DEVICE
Wired connection 1  33424e5b-2b3d-32bc-b8a8-ac48620fd6fe  802-3-ethernet  eth0
eth1                e5e67bba-e114-4426-ba5f-59e58f0adeed  802-3-ethernet  eth1
Wired connection 2  baceab37-6abd-3c3e-a886-5b1513017d6b  802-3-ethernet  —
修改Wired connection 2名字为home-eth1
[root@CENTOS7 network-scripts]#nmcli connection modify Wired\ connection\ 2 con-name home-eth1
[root@CENTOS7 network-scripts]#nmcli connection show
NAME                UUID                                  TYPE            DEVICE
Wired connection 1  33424e5b-2b3d-32bc-b8a8-ac48620fd6fe  802-3-ethernet  eth0
eth1                e5e67bba-e114-4426-ba5f-59e58f0adeed  802-3-ethernet  eth1
home-eth1           baceab37-6abd-3c3e-a886-5b1513017d6b  802-3-ethernet  —
[root@CENTOS7 network-scripts]#ls
ifcfg-eth1       ifdown-ipv6      ifdown-tunnel  ifup-isdn    ifup-TeamPort
ifcfg-home-eth1  ifdown-isdn      ifup           ifup-plip    ifup-tunnel
修改home-eth1为静态地址
[root@CENTOS7 network-scripts]#nmcli connection modify home-eth1 ipv4.addresses 172.20.0.8/16 ipv4.gateway 172.20.0.1 ipv4.dns 114.114.114.114 ipv4.dns 223.5.5.5 ipv4.method manual
[root@CENTOS7 network-scripts]#nmcli connection up home-eth1
Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/4)
[root@CENTOS7 network-scripts]#ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.30.101  netmask 255.255.255.0  broadcast 192.168.30.255
        inet6 fe80::f620:6ab3:e2e5:44  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:45:bf:14  txqueuelen 1000  (Ethernet)
        RX packets 2241  bytes 202014 (197.2 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 1608  bytes 230065 (224.6 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
eth1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.20.0.8  netmask 255.255.0.0  broadcast 172.20.255.255
        inet6 fe80::7d06:b095:d0e9:8bfa  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:45:bf:1e  txqueuelen 1000  (Ethernet)
        RX packets 12408  bytes 1827768 (1.7 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 246  bytes 31464 (30.7 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
复制一份直接修改配置文件:
[root@CENTOS7 network-scripts]#cp ifcfg-home-eth1 ifcfg-home1-eth1
[root@CENTOS7 network-scripts]#ls
ifcfg-eth1        ifdown-ippp    ifdown-TeamPort  ifup-ipv6    ifup-Team
ifcfg-home1-eth1  ifdown-ipv6    ifdown-tunnel    ifup-isdn    ifup-TeamPort
ifcfg-home-eth1   ifdown-isdn    ifup             ifup-plip    ifup-tunnel
[root@CENTOS7 network-scripts]#vim ifcfg-home1-eth1
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=none
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=home1-eth1
ONBOOT=yes
AUTOCONNECT_PRIORITY=-999
IPADDR=172.20.0.5
PREFIX=16
GATEWAY=172.20.0.1
DNS1=223.5.5.5
文件修改完成后   ,    看不到刚刚复制完成的文件
[root@CENTOS7 network-scripts]#nmcli connection show
NAME                UUID                                  TYPE            DEVICE
Wired connection 1  33424e5b-2b3d-32bc-b8a8-ac48620fd6fe  802-3-ethernet  eth0
eth1                e5e67bba-e114-4426-ba5f-59e58f0adeed  802-3-ethernet  eth1
home-eth1           baceab37-6abd-3c3e-a886-5b1513017d6b  802-3-ethernet  —
用[root@CENTOS7 network-scripts]#nmcli connection  reload  从新加载一下
[root@CENTOS7 network-scripts]#nmcli connection show
NAME                UUID                                  TYPE            DEVICE
Wired connection 1  33424e5b-2b3d-32bc-b8a8-ac48620fd6fe  802-3-ethernet  eth0
eth1                e5e67bba-e114-4426-ba5f-59e58f0adeed  802-3-ethernet  eth1
home-eth1           baceab37-6abd-3c3e-a886-5b1513017d6b  802-3-ethernet  —
home1-eth1          e7f691d1-692a-9f73-a363-87e1e480a545  802-3-ethernet  —
就能看到这个文件了。
删除不想要的配置文件
[root@CENTOS7 network-scripts]#nmcli connection delete  home-eth1
Connection ‘home-eth1’ (baceab37-6abd-3c3e-a886-5b1513017d6b) successfully deleted.
[root@CENTOS7 network-scripts]#nmcli connection delete  home1-eth1
Connection ‘home1-eth1’ (e7f691d1-692a-9f73-a363-87e1e480a545) successfully deleted.
[root@CENTOS7 network-scripts]#ls    文件已经删除
ifcfg-eth1   ifdown-isdn      ifup          ifup-plip      ifup-tunnel
ifcfg-lo     ifdown-post      ifup-aliases  ifup-plusb     ifup-wireless
[root@CENTOS7 network-scripts]#nmcli connection show      文件已经删除
NAME                UUID                                  TYPE            DEVICE
Wired connection 1  33424e5b-2b3d-32bc-b8a8-ac48620fd6fe  802-3-ethernet  eth0
eth1                e5e67bba-e114-4426-ba5f-59e58f0adeed  802-3-ethernet  eth1
使用nmcli 停用网卡
[root@CENTOS7 network-scripts]#nmcli device disconnect eth1
Device ‘eth1’ successfully disconnected.
[root@CENTOS7 network-scripts]#ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.30.101  netmask 255.255.255.0  broadcast 192.168.30.255
        inet6 fe80::f620:6ab3:e2e5:44  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:45:bf:14  txqueuelen 1000  (Ethernet)
        RX packets 3187  bytes 283149 (276.5 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 2187  bytes 313340 (305.9 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
eth1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        ether 00:0c:29:45:bf:1e  txqueuelen 1000  (Ethernet)
        RX packets 19452  bytes 2931408 (2.7 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 293  bytes 37871 (36.9 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1  (Local Loopback)
        RX packets 84  bytes 9828 (9.5 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 84  bytes 9828 (9.5 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
[root@CENTOS7 network-scripts]#ip link
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT qlen 1000
    link/ether 00:0c:29:45:bf:14 brd ff:ff:ff:ff:ff:ff
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT qlen 1000
    link/ether 00:0c:29:45:bf:1e brd ff:ff:ff:ff:ff:ff
启用eth1
root@CENTOS7 network-scripts]#nmcli device connect eth1
Device ‘eth1’ successfully activated with ‘e5e67bba-e114-4426-ba5f-59e58f0adeed’.
使用nmcli显示网卡的详细信息
[root@CENTOS7 network-scripts]#nmcli connection show eth1
connection.id:                          eth1
connection.uuid:                        e5e67bba-e114-4426-ba5f-59e58f0adeed
connection.stable-id:                   —
connection.interface-name:              eth1
connection.type:                        802-3-ethernet
connection.autoconnect:                 yes
connection.autoconnect-priority:        0
connection.autoconnect-retries:         -1 (default)
connection.timestamp:                   1525330988
connection.read-only:                   no
connection.permissions:                 —
connection.zone:                        —
connection.master:                      —
connection.slave-type:                  —
connection.autoconnect-slaves:          -1 (default)
connection.secondaries:                 —
connection.gateway-ping-timeout:        0
connection.metered:                     unknown
connection.lldp:                        -1 (default)
802-3-ethernet.port:                    —
802-3-ethernet.speed:                   0
802-3-ethernet.duplex:                  —
802-3-ethernet.auto-negotiate:          no
802-3-ethernet.mac-address:             —
802-3-ethernet.cloned-mac-address:      —
802-3-ethernet.generate-mac-address-mask:–
802-3-ethernet.mac-address-blacklist:   —
802-3-ethernet.mtu:                     auto
802-3-ethernet.s390-subchannels:        —
802-3-ethernet.s390-nettype:            —
802-3-ethernet.s390-options:            —
802-3-ethernet.wake-on-lan:             1 (default)
802-3-ethernet.wake-on-lan-password:    —
ipv4.method:                            auto
ipv4.dns:                               —
ipv4.dns-search:                        —
ipv4.dns-options:                       (default)
ipv4.dns-priority:                      0
ipv4.addresses:                         —
ipv4.gateway:                           —
ipv4.routes:                            —
ipv4.route-metric:                      -1
ipv4.ignore-auto-routes:                no
ipv4.ignore-auto-dns:                   no
ipv4.dhcp-client-id:                    —
ipv4.dhcp-timeout:                      0
ipv4.dhcp-send-hostname:                yes
ipv4.dhcp-hostname:                     —
ipv4.dhcp-fqdn:                         —
ipv4.never-default:                     no
ipv4.may-fail:                          yes
ipv4.dad-timeout:                       -1 (default)
ipv6.method:                            auto
ipv6.dns:                               —
ipv6.dns-search:                        —
ipv6.dns-options:                       (default)
ipv6.dns-priority:                      0
ipv6.addresses:                         —
ipv6.gateway:                           —
ipv6.routes:                            —
ipv6.route-metric:                      -1
ipv6.ignore-auto-routes:                no
ipv6.ignore-auto-dns:                   no
ipv6.never-default:                     no
ipv6.may-fail:                          yes
ipv6.ip6-privacy:                       -1 (unknown)
ipv6.addr-gen-mode:                     stable-privacy
ipv6.dhcp-send-hostname:                yes
ipv6.dhcp-hostname:                     —
ipv6.token:                             —
proxy.method:                           none
proxy.browser-only:                     no
proxy.pac-url:                          —
proxy.pac-script:                       —
GENERAL.NAME:                           eth1
GENERAL.UUID:                           e5e67bba-e114-4426-ba5f-59e58f0adeed
GENERAL.DEVICES:                        eth1
GENERAL.STATE:                          activated
GENERAL.DEFAULT:                        yes
GENERAL.DEFAULT6:                       no
GENERAL.VPN:                            no
GENERAL.ZONE:                           —
GENERAL.DBUS-PATH:                      /org/freedesktop/NetworkManager/ActiveConnection/6
GENERAL.CON-PATH:                       /org/freedesktop/NetworkManager/Settings/4
GENERAL.SPEC-OBJECT:                    —
GENERAL.MASTER-PATH:                    —
IP4.ADDRESS[1]:                         172.20.109.255/16
IP4.GATEWAY:                            172.20.0.1
IP4.DNS[1]:                             223.5.5.5
IP4.DNS[2]:                             223.6.6.6
IP4.DOMAIN[1]:                          magedu.com
DHCP4.OPTION[1]:                        requested_routers = 1
DHCP4.OPTION[2]:                        requested_domain_search = 1
DHCP4.OPTION[3]:                        dhcp_server_identifier = 172.20.0.1
DHCP4.OPTION[4]:                        requested_time_offset = 1
DHCP4.OPTION[5]:                        requested_domain_name = 1
DHCP4.OPTION[6]:                        filename = pxelinux.0
DHCP4.OPTION[7]:                        requested_rfc3442_classless_static_routes = 1
DHCP4.OPTION[8]:                        requested_classless_static_routes = 1
DHCP4.OPTION[9]:                        requested_wpad = 1
DHCP4.OPTION[10]:                       requested_broadcast_address = 1
DHCP4.OPTION[11]:                       next_server = 172.20.0.1
DHCP4.OPTION[12]:                       broadcast_address = 172.20.255.255
DHCP4.OPTION[13]:                       requested_interface_mtu = 1
DHCP4.OPTION[14]:                       requested_subnet_mask = 1
DHCP4.OPTION[15]:                       expiry = 1525417388
DHCP4.OPTION[16]:                       dhcp_message_type = 5
DHCP4.OPTION[17]:                       ip_address = 172.20.109.255
DHCP4.OPTION[18]:                       routers = 172.20.0.1
DHCP4.OPTION[19]:                       domain_name = magedu.com
DHCP4.OPTION[20]:                       requested_static_routes = 1
DHCP4.OPTION[21]:                       requested_nis_servers = 1
DHCP4.OPTION[22]:                       requested_ntp_servers = 1
DHCP4.OPTION[23]:                       requested_domain_name_servers = 1
DHCP4.OPTION[24]:                       dhcp_lease_time = 86400
DHCP4.OPTION[25]:                       domain_name_servers = 223.5.5.5 223.6.6.6
DHCP4.OPTION[26]:                       requested_ms_classless_static_routes = 1
DHCP4.OPTION[27]:                       subnet_mask = 255.255.0.0
DHCP4.OPTION[28]:                       network_number = 172.20.0.0
DHCP4.OPTION[29]:                       requested_host_name = 1
DHCP4.OPTION[30]:                       requested_nis_domain = 1
IP6.ADDRESS[1]:                         fe80::1ac:8bc5:45a2:ba5c/64
IP6.GATEWAY:                            —
网络配置文件
?设备配置被保存在文本文件中
? /etc/sysconfig/network-scripts/ifcfg-<name>
? 帮助文档列出完整选项列表:/usr/share/doc/initcripts-
*/sysconfig.txt
动态配置                             静态配置
DEVICE=ethX                         DEVICE=ethX
HWADDR=0:02:8A:A6:30:45             HWADDR=0:02:8A:A6:30:45
BOOTPROTO=dhcp ONBOOT=yes           IPADDR=192.168.0.123
Type=Ethernet                       NETMASK=255.255.255.0
                                    GATEWAY=192.168.0.254
                                    ONBOOT=yes
                                    Type=Ethernet
 nmcli命令
 ?修改连接配置后,需要重新加载配置
nmcli con reload
nmcli con down “system eth0” 可被自动激活
nmcli con up “system eth0”
nmcli dev dis eth0 禁用网卡,访止被自动激活
?图形工具
nm-connection-editor
?字符工具
nmtui
nmtui-connect
nmtui-edit
nmtui-hostname
在centos7中有专门的命令
hostnamectl set-hostname centos74.magedu.com
但是要自己去修改 vim /etc/hosts
nmcli实现bonding
? 添加bonding接口
nmcli con add type bond con-name mybond0 ifname mybond0 mode active-backup
? 添加从属接口
nmcli con add type bond-slave ifname ens7 master mybond0
nmcli con add type bond-slave ifname ens3 master mybond0
注:如无为从属接口提供连接名,则该名称是接口名称加类型构成
? 要启动绑定,则必须首先启动从属接口
nmcli con up bond-slave-eth0
nmcli con up bond-slave-eth1
? 启动绑定
nmcli con up mybond0
网络组Network Teaming
?网络组:是将多个网卡聚合在一起方法,从而实现冗错和提高吞吐量
?网络组不同于旧版中bonding技术,提供更好的性能和扩展性
?网络组由内核驱动和teamd守护进程实现.
?多种方式runner
broadcast
roundrobin
activebackup
loadbalance
lacp (implements the 802.3ad Link Aggregation Control Protocol)
网络组
?启动网络组接口不会自动启动网络组中的port接口
?启动网络组接口中的port接口总会自动启动网络组接口
?禁用网络组接口会自动禁用网络组中的port接口
?没有port接口的网络组接口可以启动静态IP连接
?启用DHCP连接时,没有port接口的网络组会等待port接口的加入
创建网络组接口
?nmcli con add type team con-name  CNAME ifname INAME [config JSON ]
CNAME 连接名, INAME 接口名
JSON 指定runner方式
格式:'{“runner”: {“name”: ” METHOD “}}’
METHOD 可以是broadcast, roundrobin,
activebackup, loadbalance, lacp
创建port接口
?nmcli con add type team-slave con-name  CNAME ifname INAME master
TEAM
CNAME 连接名
INAME 网络接口名
TEAM 网络组接口名
?连接名若不指定,默认为team-slave- IFACE
?nmcli dev dis  INAME
?nmcli con up  CNAME
INAME 设备名 CNAME 网络组接口名或port接口
网络组示例
?nmcli con add type team con-name team0 ifname team0 config
‘{“runner”: {“name”: “loadbalance”}}’
?nmcli con mod team0 ipv4.addresses 192.168.1.100/24
?nmcli con mod team0 ipv4.method manual
?nmcli con add con-name team0-eth1 type team-slave ifname eth1
master team0
?nmcli con add con-name team0-eth2 type team-slave ifname eth2
master team0
?nmcli con up team0
?nmcli con up team0-eth1
?nmcli con up team0-eth2
?teamdctl team0 state; nmcli dev dis eth1
实验:创建网络组
?ip link
?nmcli con add type team con-name team0 ifname team0 config
‘{“runner”: {“name”: “activebackup”}}’
?nmcli con mod team0 ipv4.addresses ‘192.168.0.100/24’
?nmcli con mod team0 ipv4.method manual
?nmcli con add con-name team0-port1 type team-slave ifname eth1
master team0
?nmcli con add con-name team0-port2 type team-slave ifname eth2
master team0
?teamdctl team0 state
实验:创建网络组
?ping -I team0 192.168.0.254
?nmcli dev dis eno1
?teamdctl team0 state
?nmcli con up team0-port1
?nmcli dev dis eno2
?teamdctl team0 state
?nmcli con up team0-port2
?teamdctl team0 state
网桥
?桥接:把一台机器上的若干个网络接口“连接”起来。其结果是,其中一个网
口收到的报文会被复制给其他网口并发送出去。以使得网口之间的报文能够互
相转发。网桥就是这样一个设备,它有若干个网口,并且这些网口是桥接起来
的。与网桥相连的主机就能通过交换机的报文转发而互相通信。
?主机A发送的报文被送到交换机S1的eth0口,由于eth0与eth1、eth2桥接在一
起,故而报文被复制到eth1和eth2,并且发送出去,然后被主机B和交换机S2
接收到。而S2又会将报文转发给主机C、D。
配置实现网桥
? 创建软件网桥
nmcli con add type bridge con-name br0 ifname br0
nmcli connection modify br0 ipv4.addresses 192.168.74.100/24
ipv4.method manuall
nmcli con add type bridge-slave con-name br0-port0 ifname eth0 master
br0
? 查看网桥
cat /etc/sysconfig/network-scripts/ifcfg-br0
cat /etc/sysconfig/network-scripts/ifcfg-br0-port0
brctl show
? 删除网桥 brctl delbr br0
? 删除网桥中网卡 brctl delif eth0
? 注意:NetworkManager只支持以太网接口接口连接到网桥,不支持聚合接口
mntui 命令行中的字符文件修改
─┤ NetworkManager TUI ├──┐
                               │                         │
                               │ Please select an option │
                               │                         │
                               │ Edit a connection       │
                               │ Activate a connection   │
                               │ Set system hostname     │
                               │                         │
                               │ Quit                    │
                               │                         │
                               │                    <OK> │
                               │                         │
测试网络工具
? 在命令行下测试网络的连通性
? 显示主机名
hostname
? 测试网络连通性
ping
mtr
? 显示正确的路由表
ip route
? 确定名称服务器使用:
? nslookup
? host
? dig
? 跟踪路由
? traceroute
? tracepath
网络客户端工具
?ftp,lftp:子命令:get、mget、ls、help
lftp [-p port] [-u user[,password]] SERVER
?lftpget URL
?wget [option]… [URL]…
-q: 静默模式
-c: 断点续传
-P:保存在指定目录
-O: 保存为指定的文件名
–limit-rate=: 指定传输速率,单位K,M等
?links URL    字符界面浏览器
–dump
–source
links www.baidu.com
links www.baidu.com –source 查看百度的源码
links www.baidu.com –dump 查看所有文字
[root@CENTOS7 ~]#wget ftp://172.20.0.1/pub/ISOs/cirros-0.3.0-x86_64-disk.img –limit-rate=1024000 字节为单位   限速下载
–2018-05-03 16:19:36–  ftp://172.20.0.1/pub/ISOs/cirros-0.3.0-x86_64-disk.img
           => ‘cirros-0.3.0-x86_64-disk.img’
Connecting to 172.20.0.1:21… connected.
Logging in as anonymous … Logged in!
==> SYST … done.    ==> PWD … done.
==> TYPE I … done.  ==> CWD (1) /pub/ISOs … done.
==> SIZE cirros-0.3.0-x86_64-disk.img … 9761280
==> PASV … done.    ==> RETR cirros-0.3.0-x86_64-disk.img … done.
Length: 9761280 (9.3M) (unauthoritative)
100%[===============================================>] 9,761,280   1022KB/s   in 9.5s
2018-05-03 16:19:45 (1006 KB/s) – ‘cirros-0.3.0-x86_64-disk.img’ saved [9761280]
[root@CENTOS7 ~]#ftp 172.20.0.1
Connected to 172.20.0.1 (172.20.0.1).
220 (vsFTPd 2.2.2)
Name (172.20.0.1:root): ftp
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> pwd
257 “/”
ftp> ls
227 Entering Passive Mode (172,20,0,1,153,217).
150 Here comes the directory listing.
drwxr-xr-x   21 0        0            4096 Apr 09 10:44 pub
226 Directory send OK.
ftp> cd pub
250 Directory successfully changed.
ftp> ls
227 Entering Passive Mode (172,20,0,1,173,48).
150 Here comes the directory listing.
drwxr-xr-x   38 0        0            4096 Nov 10 07:23 Books
drwxr-xr-x    2 0        0            4096 Jan 16 07:30 Files
drwxr-xr-x    5 0        0            4096 Apr 04 05:31 ISOs
drwxr-xr-x    2 0        0            4096 Nov 10 05:46 LFS
drwxr-xr-x    2 0        0            4096 Nov 10 05:48 Oracle
drwxr-xr-x    2 0        0            4096 Nov 10 05:48 RHCE
drwxr-xr-x   12 0        0            4096 Nov 10 06:12 Sources
drwxr-xr-x   12 0        0            4096 Nov 10 07:23 Tools
drwxr-xr-x    2 0        0            4096 Nov 10 06:18 Videos
drwxr-xr-x    2 0        0            4096 Nov 10 04:30 blogs
drwxr-xr-x    3 0        0            4096 Nov 10 04:37 errata
drwxr-xr-x    2 0        0            4096 Nov 10 04:37 exam
-rw-r–r–    1 0        0          338796 Nov 10 06:18 getty
drwxr-xr-x    5 0        0            4096 Nov 10 04:37 gls
drwxr-xr-x    2 0        0            4096 Apr 09 10:44 google_containers
drwxr-xr-x    2 0        0            4096 Nov 10 04:37 images
-rw-r–r–    1 0        0          338796 Nov 10 06:18 login
drwxr-xr-x    2 0        0            4096 Nov 10 05:46 named
drwxr-xr-x    2 0        0            4096 Nov 10 05:48 pictures
drwxr-xr-x    2 0        0            4096 Nov 10 06:12 sysroot
drwxr-xr-x    3 0        0            4096 Nov 10 06:18 updates
226 Directory send OK.
ftp> cd tools
550 Failed to change directory.
ftp> cd Tools
250 Directory successfully changed.
ftp> ls
227 Entering Passive Mode (172,20,0,1,130,154).
150 Here comes the directory listing.
-rw-r–r–    1 0        0        220402254 Nov 10 06:12 Adobe Acrobat Professional 7.0.RAR
drwxr-xr-x    2 0        0            4096 Nov 10 06:12 Edraw
-rw-r–r–    1 0        0        65071840 Nov 10 06:12 EdrawSoft_Edraw_Max.zip
-rw-r–r–    1 0        0        18290688 Nov 10 06:12 FeiQ.exe
-rw-r–r–    1 0        0        39011832 Nov 10 06:12 FileFormatConverters.exe
-rw-r–r–    1 0        0         4251204 Nov 05 06:48 FileZilla_3.3.5.1_win32-setup.exe
-rw-r–r–    1 0        0         4518720 Nov 10 06:12 FileZilla_3.5.3_win32-setup.exe
-rw-r–r–    1 0        0         1620836 Nov 10 06:12 FileZilla_Server-0_9_41.exe
-rw-r–r–    1 0        0        24850592 Nov 10 06:13 Firefox-full-latest-23.0.1.4974.exe
-rw-r–r–    1 0        0         4076643 Nov 10 06:12 FlashFXP.zip
-rw-r–r–    1 0        0         6595938 Nov 10 06:13 FullSync-0.10.1-Windows.msi
-rw-r–r–    1 0        0        31168480 Nov 10 06:13 Git-2.8.1-64-bit.exe
-rw-r–r–    1 0        0        15801540 Nov 10 06:13 HttpWatch.Professional.v7.1.37.rar
-rw-r–r–    1 0        0        15814479 Nov 10 06:13 HttpWatchPro-ha-crack.zip
-rw-r–r–    1 0        0         2032280 Nov 10 06:13 MakeSignGif.rar
-rw-r–r–    1 0        0        78817269 Nov 10 06:13 Mindmanager_9.1.157.zip
-rw-r–r–    1 0        0        17261852 Nov 10 06:13 Navicat.for.MySQL.Enterprise.v10.0.8.rar
-rw-r–r–    1 0        0        31022640 Nov 10 06:13 Opera_15.0.1147.141_Setup.exe
-rw-r–r–    1 0        0         3678601 Nov 10 06:13 SQL-Front_Setup.exe
-rw-r–r–    1 0        0        17779313 Nov 10 06:13 SQLyog Ultimate 9.6.2.0.zip
-rw-r–r–    1 0        0         6315838 Nov 10 06:13 SQLyog_Enterprise.rar
-rw-r–r–    1 0        0        59915640 Nov 05 06:48 SecureCRT and SecureFX v8.0.1 build 1082 正式版.rar
-rw-r–r–    1 0        0        10739967 Nov 10 06:13 SecureCRT_HH_x86_7.0.0.326_PortableSoft.rar
-rw-r–r–    1 0        0         9256915 Nov 10 06:13 Securecrt+6.0.2+build+260.rar
-rw-r–r–    1 0        0        69387314 Nov 10 06:13 ToadForMySQL_Beta_6.7.0.1273.zip
-rw-r–r–    1 0        0        565726726 Nov 10 06:18 VMwareFusion603.dmg
-rw-r–r–    1 0        0        31723343 Nov 10 06:13 VanDyke SecureCRT v7.2.6 with Keygen.rar
-rw-r–r–    1 0        0        14580269 Nov 10 06:13 VanDyke.SecureCRT.v7.0.0.326.Incl.Patch.And.Keymaker-ZWT (1).rar
-rw-r–r–    1 0        0        111197384 Nov 10 06:14 VirtualBox-4.3.24-98716-Win.1425444683.exe
-rw-r–r–    1 0        0        55118440 Nov 10 06:13 Visio2003_SP3.zip
-rw-r–r–    1 0        0         1456984 Nov 10 06:17 WinRAR_3.90_SC.exe
-rw-r–r–    1 0        0        29857792 Nov 10 06:17 Wireshark-win64-1.12.7.exe
-rw-r–r–    1 0        0        93801639 Nov 10 06:18 Xmanager Enterprise 4 Build 0232.rar
-rw-r–r–    1 0        0        52437791 Nov 05 06:49 Xmanager Enterprise 5 Build 0576 & Keygen.rar
-rw-r–r–    1 0        0        85509672 Nov 10 06:12 avira_antivirus_premium_zhcn.exe
-rw-r–r–    1 0        0            1873 Nov 10 06:12 avira_p_20130108.rar
drwxr-xr-x    2 0        0            4096 Nov 10 06:12 camtasia 6.0.2
-rw-r–r–    1 0        0               0 Nov 10 06:12 down.php_softid=432463
-rw-r–r–    1 0        0        44349411 Nov 10 06:12 edrawmax.zip
-rw-r–r–    1 0        0         4275944 Nov 10 06:13 lantern-installer-beta.exe
drwxr-xr-x    2 0        0            4096 Nov 10 06:13 ldapbrowser
-rw-r–r–    1 0        0         9653716 Nov 10 06:13 mySQLYogEnterprise.rar
-rw-r–r–    1 0        0         7945210 Nov 10 06:13 npp.6.6.9.Installer.1410249599.exe
-rw-r–r–    1 0        0        12883976 Nov 10 06:13 picpick_inst.exe
-rw-r–r–    1 0        0          495616 Nov 10 06:13 putty.exe
-rw-r–r–    1 0        0        20213228 Nov 10 06:13 sandcat-browser-2.02-beta.zip
-rw-r–r–    1 0        0         8888512 Nov 10 06:13 sogou_wubi_20a.exe
drwxr-xr-x    2 0        0            4096 Nov 10 06:13 sublime
-rw-r–r–    1 0        0         5118120 Nov 10 06:13 tigervnc-1.1.90.exe
-rw-r–r–    1 0        0              29 Nov 10 06:13 visio-2003-sn.txt
-rw-r–r–    1 0        0        30503216 Nov 10 06:13 vlc-2.2.3-win32.exe
drwxr-xr-x    2 0        0            4096 Nov 05 06:48 vmware
drwxr-xr-x    2 0        0            4096 Nov 10 06:14 vmware 11
drwxr-xr-x    2 0        0            4096 Nov 10 06:14 vmware 9
drwxr-xr-x    2 0        0            4096 Nov 10 06:16 vmware12
drwxr-xr-x    2 0        0            4096 Nov 10 06:17 vnc
drwxr-xr-x    2 0        0            4096 Nov 10 06:17 vnc-win32
-rw-r–r–    1 0        0        158015528 Nov 10 06:17 wps-office-8.1.0.3724-0.1.b1p2.i686.rpm
-rw-r–r–    1 0        0          437906 Nov 05 06:48 屏幕画笔 Pointofix 1.7 Portable.exe
226 Directory send OK.
ftp> get putty.exe
local: putty.exe remote: putty.exe
227 Entering Passive Mode (172,20,0,1,171,109).
150 Opening BINARY mode data connection for putty.exe (495616 bytes).
226 Transfer complete.
495616 bytes received in 0.0917 secs (5406.58 Kbytes/sec)
ftp> !ls                                                    !ls查看本机的文件,ls查看的是FTP中的文件
11.sh f1       Music  Videos
80.sh f11       Pictures   vsftpd-3.0.2-22.el7.x86_64.rpm
anaconda-ks.cfg  fff       Public  yesno.sh
bin ff.sh       putty.exe
Desktop id.sh       reset.sh
Documents initial-setup-ks.cfg  Templates
ftp> put 11.sh
local: 11.sh remote: 11.sh
227 Entering Passive Mode (172,20,0,1,142,194).
550 Permission denied.
ftp> ls
227 Entering Passive Mode (172,20,0,1,21,218).
150 Here comes the directory listing.
-rw-r–r–    1 0        0        220402254 Nov 10 06:12 Adobe Acrobat Professional 7.0.RAR
drwxr-xr-x    2 0        0            4096 Nov 10 06:12 Edraw
-rw-r–r–    1 0        0        65071840 Nov 10 06:12 EdrawSoft_Edraw_Max.zip
-rw-r–r–    1 0        0        18290688 Nov 10 06:12 FeiQ.exe
-rw-r–r–    1 0        0        39011832 Nov 10 06:12 FileFormatConverters.exe
-rw-r–r–    1 0        0         4251204 Nov 05 06:48 FileZilla_3.3.5.1_win32-setup.exe
-rw-r–r–    1 0        0         4518720 Nov 10 06:12 FileZilla_3.5.3_win32-setup.exe
-rw-r–r–    1 0        0         1620836 Nov 10 06:12 FileZilla_Server-0_9_41.exe
-rw-r–r–    1 0        0        24850592 Nov 10 06:13 Firefox-full-latest-23.0.1.4974.exe
-rw-r–r–    1 0        0         4076643 Nov 10 06:12 FlashFXP.zip
-rw-r–r–    1 0        0         6595938 Nov 10 06:13 FullSync-0.10.1-Windows.msi
-rw-r–r–    1 0        0        31168480 Nov 10 06:13 Git-2.8.1-64-bit.exe
-rw-r–r–    1 0        0        15801540 Nov 10 06:13 HttpWatch.Professional.v7.1.37.rar
-rw-r–r–    1 0        0        15814479 Nov 10 06:13 HttpWatchPro-ha-crack.zip
-rw-r–r–    1 0        0         2032280 Nov 10 06:13 MakeSignGif.rar
-rw-r–r–    1 0        0        78817269 Nov 10 06:13 Mindmanager_9.1.157.zip
-rw-r–r–    1 0        0        17261852 Nov 10 06:13 Navicat.for.MySQL.Enterprise.v10.0.8.rar
-rw-r–r–    1 0        0        31022640 Nov 10 06:13 Opera_15.0.1147.141_Setup.exe
-rw-r–r–    1 0        0         3678601 Nov 10 06:13 SQL-Front_Setup.exe
-rw-r–r–    1 0        0        17779313 Nov 10 06:13 SQLyog Ultimate 9.6.2.0.zip
-rw-r–r–    1 0        0         6315838 Nov 10 06:13 SQLyog_Enterprise.rar
-rw-r–r–    1 0        0        59915640 Nov 05 06:48 SecureCRT and SecureFX v8.0.1 build 1082 正式版.rar
-rw-r–r–    1 0        0        10739967 Nov 10 06:13 SecureCRT_HH_x86_7.0.0.326_PortableSoft.rar
-rw-r–r–    1 0        0         9256915 Nov 10 06:13 Securecrt+6.0.2+build+260.rar
-rw-r–r–    1 0        0        69387314 Nov 10 06:13 ToadForMySQL_Beta_6.7.0.1273.zip
-rw-r–r–    1 0        0        565726726 Nov 10 06:18 VMwareFusion603.dmg
-rw-r–r–    1 0        0        31723343 Nov 10 06:13 VanDyke SecureCRT v7.2.6 with Keygen.rar
-rw-r–r–    1 0        0        14580269 Nov 10 06:13 VanDyke.SecureCRT.v7.0.0.326.Incl.Patch.And.Keymaker-ZWT (1).rar
-rw-r–r–    1 0        0        111197384 Nov 10 06:14 VirtualBox-4.3.24-98716-Win.1425444683.exe
-rw-r–r–    1 0        0        55118440 Nov 10 06:13 Visio2003_SP3.zip
-rw-r–r–    1 0        0         1456984 Nov 10 06:17 WinRAR_3.90_SC.exe
-rw-r–r–    1 0        0        29857792 Nov 10 06:17 Wireshark-win64-1.12.7.exe
-rw-r–r–    1 0        0        93801639 Nov 10 06:18 Xmanager Enterprise 4 Build 0232.rar
-rw-r–r–    1 0        0        52437791 Nov 05 06:49 Xmanager Enterprise 5 Build 0576 & Keygen.rar
-rw-r–r–    1 0        0        85509672 Nov 10 06:12 avira_antivirus_premium_zhcn.exe
-rw-r–r–    1 0        0            1873 Nov 10 06:12 avira_p_20130108.rar
drwxr-xr-x    2 0        0            4096 Nov 10 06:12 camtasia 6.0.2
-rw-r–r–    1 0        0               0 Nov 10 06:12 down.php_softid=432463
-rw-r–r–    1 0        0        44349411 Nov 10 06:12 edrawmax.zip
-rw-r–r–    1 0        0         4275944 Nov 10 06:13 lantern-installer-beta.exe
drwxr-xr-x    2 0        0            4096 Nov 10 06:13 ldapbrowser
-rw-r–r–    1 0        0         9653716 Nov 10 06:13 mySQLYogEnterprise.rar
-rw-r–r–    1 0        0         7945210 Nov 10 06:13 npp.6.6.9.Installer.1410249599.exe
-rw-r–r–    1 0        0        12883976 Nov 10 06:13 picpick_inst.exe
-rw-r–r–    1 0        0          495616 Nov 10 06:13 putty.exe
-rw-r–r–    1 0        0        20213228 Nov 10 06:13 sandcat-browser-2.02-beta.zip
-rw-r–r–    1 0        0         8888512 Nov 10 06:13 sogou_wubi_20a.exe
drwxr-xr-x    2 0        0            4096 Nov 10 06:13 sublime
-rw-r–r–    1 0        0         5118120 Nov 10 06:13 tigervnc-1.1.90.exe
-rw-r–r–    1 0        0              29 Nov 10 06:13 visio-2003-sn.txt
-rw-r–r–    1 0        0        30503216 Nov 10 06:13 vlc-2.2.3-win32.exe
drwxr-xr-x    2 0        0            4096 Nov 05 06:48 vmware
drwxr-xr-x    2 0        0            4096 Nov 10 06:14 vmware 11
drwxr-xr-x    2 0        0            4096 Nov 10 06:14 vmware 9
drwxr-xr-x    2 0        0            4096 Nov 10 06:16 vmware12
drwxr-xr-x    2 0        0            4096 Nov 10 06:17 vnc
drwxr-xr-x    2 0        0            4096 Nov 10 06:17 vnc-win32
-rw-r–r–    1 0        0        158015528 Nov 10 06:17 wps-office-8.1.0.3724-0.1.b1p2.i686.rpm
-rw-r–r–    1 0        0          437906 Nov 05 06:48 屏幕画笔 Pointofix 1.7 Portable.exe
226 Directory send OK.
ftp> mget wps*                           mget下载多个文件,mput上传多个文件
mget wps-office-8.1.0.3724-0.1.b1p2.i686.rpm? y
227 Entering Passive Mode (172,20,0,1,250,49).
150 Opening BINARY mode data connection for wps-office-8.1.0.3724-0.1.b1p2.i686.rpm (158015528 bytes).
226 Transfer complete.
158015528 bytes received in 32.6 secs (4840.51 Kbytes/sec)
ftp> ^C
ftp>
lftp带颜色比ftp好用
在脚本中直接下载
lftpget ftp://172.20.0.1/pub/Tools/picpick_inst.exe  只支持ftp下载
wget ftp://172.20.0.1/pub/Tools/picpick_inst.exe    支持所有的ftp http等下载
进程概念
? 内核的功用:进程管理、文件系统、网络功能、内存管理、驱动程序、安全功能等
? Process: 运行中的程序的一个副本,是被载入内存的一个指令集合
进程ID(Process ID,PID)号码被用来标记各个进程
UID、GID、和SELinux语境决定对文件系统的存取和访问权限,
通常从执行进程的用户来继承
存在生命周期
? task struct:Linux内核存储进程信息的数据结构格式,task struct 任务结构
? task list:多个任务的的task struct组成的链表
? 进程创建:
init:第一个进程
父子关系
进程:都由其父进程创建,CoW(copy on write)  写时复制。
fork()生成子进程, clone()可以生成子进程也都可以生成兄弟进程。
程序和进程的区别:
程序表现为磁盘上的文件,静态的没有生命期。一个进程对应一个程序,一个程序可以对应多个进程。
进程是一个动态的概念,有生命期。
当父进程生成一个子进程的时候系统会生成一个新的子进程信息,但是他们处在同一个内存空间,只有子进程数据发生变化的时候才生成第二块内存来单独存放子进程。
进程的基本状态
?创建状态:进程在创建时需要申请一个空白PCB(process control block进程控
制块),向其中填写控制和管理进程的信息,完成资源分配。如果创建工作无法完
成,比如资源无法满足,就无法被调度运行,把此时进程所处状态称为创建状态
?就绪状态:进程已准备好,已分配到所需资源,只要分配到CPU就能够立即运行
?执行状态:进程处于就绪状态被调度后,进程进入执行状态
?阻塞状态:正在执行的进程由于某些事件(I/O请求,申请缓存区失败)而暂时
无法运行,进程受到阻塞。在满足请求时进入就绪状态等待系统调用
?终止状态:进程结束,或出现错误,或被系统终止,进入终止状态。无法再执行
状态之间转换六种情况
?运行——>就绪:1,主要是进程占用CPU的时间过长,而系统分配给该进程占
用CPU的时间是有限的;2,在采用抢先式优先级调度算法的系统中,当有更高
优先级的进程要运行时,该进程就被迫让出CPU,该进程便由执行状态转变为
就绪状态。
?就绪——>运行:运行的进程的时间片用完,调度就转到就绪队列中选择合适
的进程分配CPU
?运行——>阻塞:正在执行的进程因发生某等待事件而无法执行,则进程由执
行状态变为阻塞状态,如发生了I/O请求
?阻塞——>就绪:进程所等待的事件已经发生,就进入就绪队列
?以下两种状态是不可能发生的:
?阻塞——>运行:即使给阻塞进程分配CPU,也无法执行,操作系统在进行调
度时不会从阻塞队列进行挑选,而是从就绪队列中选取
?就绪——>阻塞:就绪态根本就没有执行,谈不上进入阻塞态
ps aux 可以查看系统正在运行的进程的各种状态
以前的系统使用协作式多任务,协作式多任务就是指一个进程霸占CPU直到进程结束。
现在的系统使用抢占式多任务,按时间片分配,时间片一到就必须释放CPU给别的进程使用。
进程优先级
?进程优先级:
系统优先级:数字越小,优先级越高
0-139(CentOS4,5)
各有140个运行队列和过期队列
0-98,99(CentOS6)
实时优先级: 99-0 值最大优先级最高
nice值:-20到19,对应系统优先级100-139或99
?Big O:时间复杂度,用时和规模的关系
O(1), O(logn), O(n)线性, O(n^2)抛物线, O(2^n)
进程相关概念
? 进程内存:
Page Frame: 页框,用存储页面数据,存储Page 4k
LRU:Least Recently Used 近期最少使用算法,释放内存
物理地址空间和线性地址空间
MMU:Memory Management Unit负责转换线性和物理地址
TLB:Translation Lookaside Buffer 翻译后备缓冲器,用于保存虚拟地址和物理地址
映射关系的缓存
? IPC: Inter Process Communication
同一主机: signal:信号
shm: shared memory
semaphore:信号量,一种计数器
不同主机:socket: IP和端口号
RPC: remote procedure call
MQ:消息队列,Kafka,ActiveMQ
LRU算法   缓存的算法
?假设序列为 4 3 4 2 3 1 4 2
物理块有3个,则
?第1轮 4调入内存 4
?第2轮 3调入内存 3 4
?第3轮 4调入内存 4 3
?第4轮 2调入内存 2 4 3
?第5轮 3调入内存 3 2 4
?第6轮 1调入内存 1 3 2
?第7轮 4调入内存 4 1 3
?第8轮 2调入内存 2 4 1
LRU的变种算法:访问一次不上移,访问多次才上移。
对于一个应用程序来说,实实在在的cpu给应用程序的空间,叫物理空间
而对于应用程序来说,觉得自己拥有全部空间,这就叫做线性空间。
MMU :   用来负责转换线性内存和物理内存
LTB:存放在cup中,用来保存虚拟地址和物理地址的映射关系。
一个应用程序运行时向cpu申请1个G的内存空间,cup发现这个程序现阶段运行只需要100M的内存空间就够了
所以CUP只给程序100M的空间,但是承若当程序需要1G的空间时会给予分配。这是承若分配内存空间和实际分配内存空间。
[root@CENTOS7 ~]#ps aux  承若的内存空间   实际的内存空间
USER        PID %CPU %MEM       VSZ              RSS TTY      STAT START   TIME COMMAND
root          1  0.0  0.4      128164              5476 ?        Ss   14:16   0:02 /usr/lib/systemd/system
一个电脑上多个进程之间如何通讯
机: signal:信号
shm: shared memory :将数据放到共有的空间中
semaphore:信号量,一种计数器:10个信号量,每一个进程占据一个信号量,当10个都用完时,等待前面的程序用完后面的程序才可以使用
不同主机:socket: IP和端口号
RPC: remote procedure call   A机器上跑的一个程序,跑了一会后到B机器上去调用B机器上的一个程序,之后在回到A机器上运行
A     B
 →
     ↓
    ←
MQ:消息队列,Kafka,ActiveMQ
将各个主机的任务消息放在Kafka服务器上,再由服务器排序,按顺序访问。
进程状态
? Linux内核:抢占式多任务
? 进程类型:
守护进程: daemon,在系统引导过程中启动的进程,和终端无关进程
前台进程:跟终端相关,通过终端启动的进程
注意:两者可相互转化
? 进程状态:
运行态:running
就绪态:ready
睡眠态:
可中断:interruptable
不可中断:uninterruptable
停止态:stopped,暂停于内存,但不会被调度,除非手动启动
僵死态:zombie,结束进程,父进程结束前,子进程不关闭
前台执行:如sleep占用终端资源
ps输出属性
? VSZ: Virtual memory SiZe,虚拟内存集,线性内存
? RSS: ReSident Size, 常驻内存集
? STAT:进程状态
R:running
S: interruptable sleeping
D: uninterruptable sleeping
T: stopped
Z: zombie
+: 前台进程
l: 多线程进程 process(各种资源的融合)  thread 线程,{}表示线程(干活的人的个数可以一个也可以多个)
L:内存分页并带锁
N:低优先级进程
<: 高优先级进程
s: session leader,会话(子进程)发起者
系统管理工具
?进程的分类:
CPU-Bound:CPU密集型,非交互   加密解密压缩解压缩都是CPU密集型
IO-Bound:IO密集型,交互       读写一个大文件
?Linux系统状态的查看及管理工具:pstree, ps, pidof, pgrep, top, htop,
glance, pmap, vmstat, dstat, kill, pkill, job, bg, fg, nohup
?pstree命令:
pstree – display a tree of processes
?ps: process state     基于快照的,每次信息可能不一样。  默认ps只显示当前一个用户一个终端开的前天进程,
ps – report a snapshot of the current processes
Linux系统各进程的相关信息均保存在/proc/PID目录下的各文件中
pstree -p 查看系统使用的进程树
ls /proc/ 可以看到好多数字,每一个数字都是一个进程的PID
[root@CENTOS7 ~]#ls /proc
1     1408  1558  1852  292  5     612   706   998          kallsyms      slabinfo
10    1410  1559  19    293  5138  614   707   999          kcore         softirqs
1006  1418  1562  2     294  539   618   708   acpi         keys          stat
1058  1420  1563  20    295  553   637   712   asound       key-users     swaps
1098  1423  1573  21    296  554   638   716   buddyinfo    kmsg          sys
11    1427  1580  22    297  555   639   725   bus          kpagecount    sysrq-trigger
1100  1432  1581  23    298  556   640   7267  cgroups      kpageflags    sysvipc
1140  1436  1583  238   3    557   641   757   cmdline      loadavg       timer_list
1151  1442  1589  239   30   558   642   8     consoles     locks         timer_stats
1154  1450  1601  24    31   559   645   8200  cpuinfo      mdstat        tty
1161  1455  1687  240   32   560   646   8239  crypto       meminfo       uptime
1168  1466  17    241   33   561   648   8320  devices      misc          version
12    1469  1726  242   377  562   649   8350  diskstats    modules       vmallocinfo
1236  1483  1733  245   400  563   650   8399  dma          mounts        vmstat
1241  1489  1742  246   404  564   656   8400  driver       mpt           zoneinfo
13    15    1753  250   405  565   657   8479  execdomains  mtrr
1333  1505  1755  251   41   566   659   8480  fb           net
1350  1507  1780  256   418  567   66    9     filesystems  pagetypeinfo
1355  1519  1796  257   43   568   671   98    fs           partitions
1359  1536  18    288   442  571   677   982   interrupts   sched_debug
1380  1538  1800  289   45   572   6806  984   iomem        schedstat
1386  1547  1801  290   457  576   7     986   ioports      scsi
1403  1551  1846  291   47   577   705   997   irq          self
[root@CENTOS7 ~]#ls /proc/1
attr        coredump_filter  gid_map    mountinfo   oom_score      schedstat  status
autogroup   cpuset           io         mounts      oom_score_adj  sessionid  syscall
auxv        cwd              limits     mountstats  pagemap        setgroups  task
cgroup      environ          loginuid   net         personality    smaps      timers
clear_refs  exe              map_files  ns          projid_map     stack      uid_map
cmdline     fd               maps       numa_maps   root           stat       wchan
comm        fdinfo           mem        oom_adj     sched          statm
[root@CENTOS7 ~]#ls /proc/1/exe -l
lrwxrwxrwx. 1 root root 0 May  3 16:00 /proc/1/exe -> /usr/lib/systemd/systemd
查看进程进程ps
? ps [OPTION]…
? 支持三种选项:
UNIX选项 如-A -e
BSD选项  如a
GNU选项  如–help
? 选项:默认显示当前终端中的进程
? a 选项包括所有终端中的进程
? x 选项包括不链接终端的进程
? u 选项显示进程所有者的信息
? f 选项显示进程树,相当于 –forest
? k| –sort 属性 对属性 排序,属性前加- 表示倒序
? o 属性… 选项显示定制的信息 pid、cmd、%cpu、%mem
? L 显示支持的属性列表
ps 命令后面跟 a 和 -a 意思是不一样的
查看进程进程ps
  ps [OPTION]…
  支持三种选项:
UNIX选项 如-A -e
BSD选项  如a
GNU选项  如–help
  选项:默认显示当前终端中的进程
  a 选项包括所有终端中的进程
  x 选项包括不链接终端的进程
  u 选项显示进程所有者的信息
  f 选项显示进程树,相当于 –forest
  k| –sort 属性 对属性 排序,属性前加- 表示倒序
  o 属性… 选项显示定制的信息 pid、cmd、%cpu、%mem
  L 显示支持的属性列表
[wang@CENTOS7 ~]$ps xa         a所有终端
 进程编号 在哪个终端上 状态    运行了几个时间片    命令
   PID    TTY          STAT     TIME              COMMAND
     1     ?            Ss        0:07             /usr/lib/systemd/systemd –switched-root –system –deserialize 21
     2     ?            S         0:00              [kthreadd]
     3     ?            S         0:00               [ksoftirqd/0]
[wang@CENTOS7 ~]$ps aux
USER        PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root          1  0.0  0.5 193700  6336 ?        Ss   08:48   0:07 /usr/lib/systemd/systemd –switched-root –system
root          2  0.0  0.0      0     0 ?        S    08:48   0:00 [kthreadd]
[wang@CENTOS7 ~]$ps auxf
USER        PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root          2  0.0  0.0      0     0 ?        S    08:48   0:00 [kthreadd]
root          3  0.0  0.0      0     0 ?        S    08:48   0:00  \_ [ksoftirqd/0]
root          5  0.0  0.0      0     0 ?        S<   08:48   0:00  \_ [kworker/0:0H]
root          6  0.0  0.0      0     0 ?        S    08:48   0:02  \_ [kworker/u256:0]
root          7  0.0  0.0      0     0 ?        S    08:48   0:01  \_ [migration/0]
[wang@CENTOS7 ~]$ps axo pid,%cpu,%mem,tty k %cpu
   PID %CPU %MEM TT
     1  0.0  0.5 ?
     2  0.0  0.0 ?
[wang@CENTOS7 ~]$ps axo pid,%cpu,%mem,tty,cmd k %mem     在centos6排序只按PID排,其他排序不好用
   PID %CPU %MEM TT       CMD
     2  0.0  0.0 ?        [kthreadd]
     3  0.0  0.0 ?        [ksoftirqd/0]
  1385  0.1 14.5 ?        /usr/bin/gnome-shell      占用内存最多的是图形界面
[root@CENTOS7 ~]#free -h
              total        used        free      shared  buff/cache   available
Mem:           1.0G        206M        513M         20M        353M        641M
Swap:          2.0G        604K        2.0G
[root@CENTOS7 ~]#init 3      关闭图形界面后使用内存变小
[root@CENTOS7 ~]#free -h
              total        used        free      shared  buff/cache   available
Mem:           1.0G        203M        517M         20M        353M        645M
Swap:          2.0G        604K        2.0G
[root@CENTOS7 ~]#ps L    查看 ps xo 后面可跟的选项,其中euser是有效的使用者,ruser真正的使用者
%cpu         %CPU
%mem         %MEM
_left        LLLLLLLL
在别的终端上运行
[wang@CENTOS7 ~]$passwd
Changing password for user wang.
Changing password for wang.
(current) UNIX password:
[root@CENTOS7 ~]#ps axo pid,cmd,euser,ruser   因为passwd上面有suid所以造成下面效果
   PID CMD                         EUSER    RUSER
  14646 passwd                      root     wang
ps常见选项
  -C cmdlist 指定命令,多个命令用,分隔
  -L 显示线程
  -e: 显示所有进程,相当于-A
  -f: 显示完整格式程序信息
  -F: 显示更完整格式的进程信息
  -H: 以进程层级格式显示进程相关信息
  -u userlist 指定有效的用户ID或名称
  -U userlist 指定真正的用户ID或名称
  -g gid或groupname 指定有效的gid或组名称
  -G gid或groupname 指定真正的gid或组名称
  -p pid 显示指pid的进程
  –ppid pid 显示属于pid的子进程
  -M 显示SELinux信息,相当于Z
[root@CENTOS7 ~]#ps -ef
UID         PID   PPID  C STIME TTY          TIME CMD
root          1      0  0 08:48 ?        00:00:08 /usr/lib/systemd/systemd –switched-root –system –deserialize 21
root          2      0  0 08:48 ?        00:00:00 [kthreadd]
[root@CENTOS7 ~]#ps -eF
UID         PID   PPID  C    SZ   RSS PSR STIME TTY          TIME CMD
root          1      0  0 50474  5860   1 08:48 ?        00:00:08 /usr/lib/systemd/systemd –switched-root –system –de
root          2      0  0     0     0   1 08:48 ?        00:00:00 [kthreadd]
[root@CENTOS7 ~]#ps -U wang    查看真是用户wang,用户开启的程序
   PID TTY          TIME CMD
  6137 ?        00:00:00 sshd
  6138 pts/0    00:00:00 bash
 13780 pts/0    00:00:00 su
 14592 ?        00:00:00 sshd
 14593 pts/1    00:00:00 bash
 14795 pts/1    00:00:00 passwd
[root@CENTOS7 ~]#ps -u wang  查看有效用户是wang,用户开启的程序
   PID TTY          TIME CMD
  6137 ?        00:00:00 sshd
  6138 pts/0    00:00:00 bash
 14592 ?        00:00:00 sshd
 14593 pts/1    00:00:00 bash
[root@CENTOS7 ~]#ps -p 14168   用进程编号查看进程是什么
   PID TTY          TIME CMD
 14168 ?        00:00:00 gnome-shell-cal
[root@CENTOS7 ~]#ps –ppid 14130     查看14130进程的子进程是谁
   PID TTY          TIME CMD
 14153 ?        00:00:00 ibus-daemon
ps输出属性
   VSZ: Virtual memory SiZe,虚拟内存集,线性内存
   RSS: ReSident Size, 常驻内存集
   STAT:进程状态
R:running
S: interruptable sleeping
D: uninterruptable sleeping
T: stopped
Z: zombie
+: 前台进程
l: 多线程进程
L:内存分页并带锁
N:低优先级进程
<: 高优先级进程
s: session leader,会话(子进程)发起者
ps
  ni: nice值
  pri: priority 优先级
  psr: processor CPU编号
  rtprio: 实时优先级
  示例:
ps axo pid,cmd,psr,ni,pri,rtprio
  常用组合:
aux
-ef
-eFH
-eo pid,tid,class,rtprio,ni,pri,psr,pcpu,stat,comm
axo stat,euid,ruid,tty,tpgid,sess,pgrp,ppid,pid,pcpu,comm
system 优先级0-99,100-139
realtime     99-0
nice               负20-19
top         RT-RT 0-39
[root@CENTOS7 ~]#ps xo pid,cmd,pri,nice,rtprio
                              pri优先级是反的,就是139-0   nice是正常的负20-19代表100-139     rtprio代表realtime99-0.-表示没有对应关系
   PID CMD                                PRI               NI RTPRIO
     1 /usr/lib/systemd/systemd —         19      0       –
     2 [kthreadd]                          19      0       –
     3 [ksoftirqd/0]                       19      0       –
     5 [kworker/0:0H]                      39  -20       –
     6 [kworker/u256:0]                    19      0       –
     7 [migration/0]                       139      –     99
程序跑起来以后调整优先级 :
renice -n -10(负10)6
[root@CENTOS7 ~]#ps xo pid,cmd,pri,nice,rtprio
14795 passwd                       19   0      –
[root@CENTOS7 ~]#renice -n -10 14795
14795 (process ID) old priority 0, new priority -10
[root@CENTOS7 ~]#ps xo pid,cmd,pri,nice,rtprio
14795 passwd                       29 -10      –
直接指定优先级:
nice -n -10 sleep 100 也可以写成 nice –10 sleep100.   nice -10 sleep是指定优先级为10
[root@CENTOS7 ~]#nice -n -10 sleep 100    直接指定sleep以nice-10的优先级运行
[root@CENTOS7 ~]#ps xo pid,cmd,pri,nice,rtprio
   PID CMD                         PRI  NI RTPRIO
 15387 sleep 100                    29 -10      –
psr 使用哪个cpu的意思,应用程序运行时,默认使用的cpu不是固定的,而是在几颗cpu来回切换。这样
来回切换并不好,会浪费cpu内存中存储的信息使效率下降。
[root@CENTOS7 ~]#watch -n 1 ‘ps -xo pid,cmd,psr’      每秒显示一次这个命令
ps示例
  查询你拥有的所有进程:
ps -x
  显示指定用户名(RUID)或用户ID的进程:
ps -fU apache
ps -fu 48
  显示指定用户名(EUID)或用户ID的进程:
ps -fu wang
ps -fu 1000
  查看以root用户权限(实际和有效ID)运行的每个进程:
ps -U root -u root
  列出某个组拥有的所有进程(实际组ID:RGID或名称):
ps -fG nginx
ps示例
  列出有效组名称(或会话)所拥有的所有进程:
ps -fg mysql
ps -fG 27
  通过进程ID来显示所属的进程:
ps -fp 1234
  以父进程ID来显示其下所有的进程,如显示父进程为1154的所有进程:
ps -f –ppid 1234
  显示指定PID的多个进程:
ps -fp 1204,1239,1263
  要按tty显示所属进程:
ps -ft pst/0
[root@CENTOS7 ~]#ps -C bash       -C cmd 显示该cmd的信息
   PID TTY          TIME CMD
  6138 pts/0    00:00:00 bash
  6448 tty2     00:00:00 bash
 13786 pts/0    00:00:00 bash
 13884 tty1     00:00:00 bash
 14593 pts/1    00:00:00 bash
 15346 pts/1    00:00:00 bash
编写2个脚本
[root@CENTOS7 ~]#vim f1.sh
#!/bin/bash
echo hello
sleep 100
如果不加#!/bin/bash
ps -C f1.sh查询不到
如果运行时用
bash f1.sh
ps -C f1.sh 也查询不到
可以一次查询多个程序
ps -Cf1.sh -C f2.sh
ps -Cf1.sh -C f2.sh o pid,%cpu,%mem,psr      查看自己写的脚本的运行情况
ps示例
?以进程树显示系统中的进程如何相互链接:
ps -e –forest
?以进程树显示指定的进程
ps -f –forest -C sshd
ps -ef –forest | grep -v grep | grep sshd
?要显示一个进程的所有线程,将显示LWP(轻量级进程)以及NLWP(轻量级进
程数)列:
ps -fL -C nginx
?要列出所有格式说明符:
ps L
?查看进程的PID,PPID,用户名和命令:
ps -eo pid,ppid,user,cmd
ps示例
?自定义格式显示文件系统组,ni值开始时间和进程的时间:
ps -p 1234 -o pid,ppid,fgroup,ni,lstart,etime
?使用其PID查找进程名称:
ps -p 1244 -o comm=
?要以其名称选择特定进程,显示其所有子进程
ps -C sshd,bash
?查找指定进程名所有的所属PID,在编写需要从std输出或文件读取PID的脚本时
这个参数很有用:
ps -C httpd,sshd -o pid=
?检查一个进程的执行时间
ps -eo comm,etime,user | grep nginx
[root@CENTOS7 ~]#ps -C f1.sh -C ping o pid,cmd,%cpu,%mem
   PID CMD                         %CPU %MEM
 16117 /bin/bash ./f1.sh            0.0  0.1
 16118 ping -f 172.20.0.1           2.5  0.1
[root@CENTOS7 ~]#ps -p 16118
   PID TTY          TIME CMD
 16118 pts/1    00:00:05 ping
[root@CENTOS7 ~]#ps -p 16118 -o comm
COMMAND
ping
[root@CENTOS7 ~]#ps -C f1.sh -C ping o pid,cmd,%cpu,%mem
   PID CMD                         %CPU %MEM
 16181 /bin/bash ./f1.sh            0.0  0.1
 16182 ping -f 192.168.30.101      98.5  0.1
[root@CENTOS7 ~]#ps -C bash -o pid=
  1886
  1957
[root@CENTOS7 ~]#ps -C gnome-shell -o %cpu=
 1.4
[root@CENTOS7 ~]#ps -eo time,etime,pid,psr,%mem,%cpu,cmd | grep “httpd”
00:00:00       02:39   2127   1  0.4  0.2 /usr/sbin/httpd -DFOREGROUND
00:00:00       02:31   2129   2  0.2  0.0 /usr/sbin/httpd -DFOREGROUND
00:00:00       02:31   2130   3  0.2  0.0 /usr/sbin/httpd -DFOREGROUND
00:00:00       02:31   2131   0  0.2  0.0 /usr/sbin/httpd -DFOREGROUND
00:00:00       02:31   2132   2  0.2  0.0 /usr/sbin/httpd -DFOREGROUND
00:00:00       02:31   2133   2  0.2  0.0 /usr/sbin/httpd -DFOREGROUND
00:00:00       00:00   2224   3  0.0  0.0 grep –color=auto httpd
[root@CENTOS7 ~]#ps xo pid,%cpu,%mem,cmd k -%mem     排序k也可以写成–sort=
   PID %CPU %MEM CMD
  1423  0.7 15.1 /usr/bin/gnome-shell
  1615  0.0  5.9 /usr/libexec/evolution-calendar-factory
  1802  0.0  5.5 /usr/libexec/evolution-calendar-factory-subprocess –factory contacts –bus-name org.gnome.evolution.da
  1815  0.0  5.5 /usr/libexec/evolution-calendar-factory-subprocess –factory local –bus-name org.gnome.evolution.datas
  1617  0.2  4.3 /usr/bin/gnome-software –gapplication-service
ps示例
  查找占用最多内存和CPU的进程:
ps -eo pid,ppid,cmd,%mem,%cpu –sort=-%mem | head
ps -eo pid,ppid,cmd,%mem,%cpu –sort=-%cpu | head
  显示安全信息:
ps -eM
ps –context
  使用以下命令以用户定义的格式显示安全信息。
ps -eo euser,ruser,suser,fuser,f,comm,label
  使用watch实用程序执行重复的输出以实现对就程进行实时的监视,如下面的命
令显示每秒钟的监视:
watch -n 1 ‘ps -eo pid,ppid,cmd,%mem,%cpu –sort=-%mem | head’
进程优先级
  进程优先级调整:
静态优先级:100-139
进程默认启动时的nice值为0,优先级为120
只有根用户才能降低nice值(提高优先性)
  nice命令:
nice [OPTION] [COMMAND [ARG]…]
  renice命令:
renice [-n] priority pid…
  查看:
ps axo pid,comm,ni
搜索进程
  最灵活:ps 选项 | 其它命令
  按预定义的模式:pgrep
pgrep [options] pattern
-u uid: effective user,生效者
-U uid: real user,真正发起运行命令者
-t terminal: 与指定终端相关的进程
-l: 显示进程名
-a: 显示完整格式的进程名
-P pid: 显示指定进程的子进程
  按确切的程序名称:/sbin/pidof
pidof bash
[root@CENTOS7 ~]#pgrep -a “httpd”   支持正在表达式
2127 /usr/sbin/httpd -DFOREGROUND
2129 /usr/sbin/httpd -DFOREGROUND
2130 /usr/sbin/httpd -DFOREGROUND
2131 /usr/sbin/httpd -DFOREGROUND
2132 /usr/sbin/httpd -DFOREGROUND
2133 /usr/sbin/httpd -DFOREGROUND
[root@CENTOS7 ~]#pgrep -at pts/1
2049 -bash
2134 su –
2138 -bash
[root@CENTOS7 ~]#pgrep -a “^ht*”
2127 /usr/sbin/httpd -DFOREGROUND
2129 /usr/sbin/httpd -DFOREGROUND
2130 /usr/sbin/httpd -DFOREGROUND
2131 /usr/sbin/httpd -DFOREGROUND
2132 /usr/sbin/httpd -DFOREGROUND
2133 /usr/sbin/httpd -DFOREGROUND
[root@CENTOS7 ~]#pidof bash            查看一个进程的进程编号
2138 2049 1957 1886 732
[root@CENTOS7 ~]#pidof httpd
2133 2132 2131 2130 2129 2127
系统工具
  uptime
显示当前时间,系统已启动的时间、当前上线人数,系统平均负载(1、5、10分
钟的平均负载,一般不会超过1)
  系统平均负载:
指在特定时间间隔内运行队列中的平均进程数
  通常每个CPU内核的当前活动进程数不大于3,那么系统的性能良好。如果每
个CPU内核的任务数大于5,那么此主机的性能有严重问题
  如果linux主机是1个双核CPU,当Load Average 为6的时候说明机器已经被
充分使用
[root@CENTOS7 ~]#uptime
当前时间     启动了多久    当前有几个用户         平均负载情况1分钟 5分钟  10分钟内cpu没有完成的任务的个数
 09:28:49     up 28 min,        3 users,        load average: 0.00,  0.01,   0.10
进程管理工具
   top:有许多内置命令:
排序:
P:以占据的CPU百分比,%CPU
M:占据内存百分比,%MEM
T:累积占据CPU时长,TIME+
首部信息显示:
uptime信息:l命令
tasks及cpu信息:t命令
cpu分别显示:1 (数字)
memory信息:m命令
退出命令:q
修改刷新时间间隔:s
终止指定进程:k
保存文件:W
top命令
   栏位信息简介
us:用户空间
sy:内核空间
ni:调整nice时间
id:空闲
wa:等待IO时间
hi:硬中断
si:软中断(模式切换)
st:虚拟机偷走的时间
进程管理工具
    选项:
-d #: 指定刷新时间间隔,默认为3秒
-b: 全部显示所有进程
-n #: 刷新多少次后退出
htop命令:EPEL源
选项:
-d #: 指定延迟时间;
-u UserName: 仅显示指定用户的进程
-s COLUME: 以指定字段进行排序
子命令:
s: 跟踪选定进程的系统调用
l: 显示选定进程打开的文件列表
a:将选定的进程绑定至某指定CPU核心
t: 显示进程树
[root@CENTOS7 ~]#top
top – 09:44:18 up 44 min,  3 users,  load average: 0.00, 0.01, 0.05
Tasks: 210 total,   1 running, 209 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.0 us,  0.1 sy,  0.0 ni, 99.8 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :  1100072 total,    88032 free,   653152 used,   358888 buff/cache
KiB Swap:  2097148 total,  2097128 free,       20 used.   238040 avail Mem
[root@CENTOS7 ~]#top -n 5 -b -d 5 -u wang
[root@CENTOS7 ~]#htop
top – 09:49:57 up 49 min,  3 users,  load average: 0.01, 0.02, 0.05
Tasks: 212 total,   1 running, 211 sleeping,   0 stopped,   0 zombie
%Cpu(s):  1.4 us,  4.1 sy,  0.0 ni, 94.6 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :  1100072 total,    82040 free,   652952 used,   365080 buff/cache
KiB Swap:  2097148 total,  2097048 free,      100 used.   235600 avail Mem
内存空间
  内存空间使用状态:
free [OPTION]
-b 以字节为单位
-m 以MB为单位
-g 以GB为单位
-h 易读格式
-o 不显示-/+buffers/cache行
-t 显示RAM + swap的总和
-s n 刷新间隔为n秒
-c n 刷新n次后即退出
清除缓存
[root@centos6 ~]#find /proc/ -name drop_caches
/proc/sys/vm/drop_caches
[root@centos6 ~]#cat /proc/sys/vm/drop_caches
0
[root@centos6 ~]#echo 1 > /proc/sys/vm/drop_caches
[root@centos6 ~]#free -h -s 2 -c 2
             total       used       free     shared    buffers     cached
Mem:          1.9G       666M       1.3G       2.4M       115M       175M
-/+ buffers/cache:       375M       1.6G
Swap:         2.0G         0B       2.0G
             total       used       free     shared    buffers     cached
Mem:          1.9G       666M       1.3G       2.4M       115M       175M
-/+ buffers/cache:       375M       1.6G
Swap:         2.0G         0B       2.0G
内存工具
   vmstat命令:虚拟内存信息
vmstat [options] [delay [count]]
vmstat 2 5
   procs:
r:可运行(正运行或等待运行)进程的个数,和核心数有关
b:处于不可中断睡眠态的进程个数(被阻塞的队列的长度)
   memory:
swpd: 交换内存的使用总量
free:空闲物理内存总量
buffer:用于buffer的内存总量
cache:用于cache的内存总量
   swap:
si:从磁盘交换进内存的数据速率(kb/s)
so:从内存交换至磁盘的数据速率(kb/s)
[root@centos6 ~]#vmstat
procs ———–memory———- —swap– —–io—- –system– —–cpu—–
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
 1  0      0 1354884 118272 179848    0    0    13     1   15   14  0  0 99  1  0
[root@centos6 ~]#vmstat 1      一秒观察一次
procs ———–memory———- —swap– —–io—- –system– —–cpu—–
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
 0  0      0 1356124 118272 179848    0    0    13     1   14   13  0  0 99  1  0
 0  0      0 1356092 118272 179848    0    0     0     0   71   48  0  0 100  0  0
 0  0      0 1356076 118272 179848    0    0     0     0   26   19  0  0 100  0  0
[root@centos6 ~]#vmstat 1 3    一秒执行一次,执行3次退出
procs ———–memory———- —swap– —–io—- –system– —–cpu—–
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
 0  0      0 1356124 118272 179848    0    0    13     1   14   13  0  0 99  1  0
 0  0      0 1356092 118272 179848    0    0     0     0   71   48  0  0 100  0  0
 0  0      0 1356076 118272 179848    0    0     0     0   26   19  0  0 100  0  0
这里io的意思是:这里的产考物是内存
IO
       bi: Blocks received from a block device (blocks/s).   出磁盘,读出磁盘
       bo: Blocks sent to a block device (blocks/s).         进磁盘,写到磁盘
 Swap
       si: Amount of memory swapped in from disk (/s).
       so: Amount of memory swapped to disk (/s).
内存工具
  iostat:统计CPU和设备IO信息
示例:iostat 1 10
  pmap命令:进程对应的内存映射
  pmap [options] pid […]
-x: 显示详细格式的信息
示例:pmap 1
  另外一种实现:
cat /proc/PID/maps
[root@CENTOS7 ~]#iostat
Linux 3.10.0-693.el7.x86_64 (CENTOS7.localdomain) 05/05/2018 _x86_64_ (4 CPU)
avg-cpu:  %user   %nice %system %iowait  %steal   %idle
           0.30    0.00    0.92    0.67    0.00   98.11
Device:            tps    kB_read/s    kB_wrtn/s    kB_read    kB_wrtn
sda               2.93       104.48        11.45     829137      90894
sdb               0.03         0.45         0.00       3536          0
sdc               0.04         0.70         0.00       5535          0
scd0              0.00         0.13         0.00       1056          0
dm-0              0.01         0.13         0.00       1036          0
dm-1              0.01         0.13         0.00       1036          0
[root@CENTOS7 ~]#pmap 2138                  详细显示bash命令中每个调用使用的真正内存是多少
2138:   -bash                               如果一个模块内存一直增大,会导致内存耗尽。这个程序有问题
0000000000400000    884K r-x– bash
00000000006dc000      4K r—- bash
00000000006dd000     36K rw— bash
00000000006e6000     24K rw—   [ anon ]
0000000000c45000   1444K rw—   [ anon ]
00007f20e6279000 103588K r—- locale-archive
00007f20ec7a2000     48K r-x– libnss_files-2.17.so
00007f20ec7ae000   2044K —– libnss_files-2.17.so
00007f20ec9ad000      4K r—- libnss_files-2.17.so
00007f20ec9ae000      4K rw— libnss_files-2.17.so
00007f20ec9af000     24K rw—   [ anon ]
00007f20ec9b5000   1760K r-x– libc-2.17.so
00007f20ecb6d000   2048K —– libc-2.17.so
00007f20ecd6d000     16K r—- libc-2.17.so
00007f20ecd71000      8K rw— libc-2.17.so
00007f20ecd73000     20K rw—   [ anon ]
00007f20ecd78000      8K r-x– libdl-2.17.so
00007f20ecd7a000   2048K —– libdl-2.17.so
00007f20ecf7a000      4K r—- libdl-2.17.so
00007f20ecf7b000      4K rw— libdl-2.17.so
00007f20ecf7c000    148K r-x– libtinfo.so.5.9
00007f20ecfa1000   2048K —– libtinfo.so.5.9
00007f20ed1a1000     16K r—- libtinfo.so.5.9
00007f20ed1a5000      4K rw— libtinfo.so.5.9
00007f20ed1a6000    132K r-x– ld-2.17.so
00007f20ed3b0000     12K rw—   [ anon ]
00007f20ed3bd000      4K rw—   [ anon ]
00007f20ed3be000     28K r–s- gconv-modules.cache
00007f20ed3c5000      8K rw—   [ anon ]
00007f20ed3c7000      4K r—- ld-2.17.so
00007f20ed3c8000      4K rw— ld-2.17.so
00007f20ed3c9000      4K rw—   [ anon ]
00007fff5dfec000    132K rw—   [ stack ]
00007fff5e0f2000      8K r-x–   [ anon ]
ffffffffff600000      4K r-x–   [ anon ]
 total           116576K
[root@CENTOS7 ~]#pmap -x 2138
2138:   -bash
                                  脏数据:没有修改完成的数据
Address           Kbytes     RSS   Dirty Mode  Mapping
0000000000400000     884     548       0 r-x– bash
00000000006dc000       4       4       4 r—- bash
00000000006dd000      36      36      36 rw— bash
[root@CENTOS7 ~]#cat /proc/2138/maps              产看文件
00400000-004dd000 r-xp 00000000 08:02 99298                              /usr/bin/bash
006dc000-006dd000 r–p 000dc000 08:02 99298                              /usr/bin/bash
006dd000-006e6000 rw-p 000dd000 08:02 99298                              /usr/bin/bash
006e6000-006ec000 rw-p 00000000 00:00 0
00c45000-00dae000 rw-p 00000000 00:00 0                                  [heap]
7f20e6279000-7f20ec7a2000 r–p 00000000 08:02 67524402                   /usr/lib/locale/locale-archive
7f20ec7a2000-7f20ec7ae000 r-xp 00000000 08:02 33792348                   /usr/lib64/libnss_files-2.17.so
7f20ec7ae000-7f20ec9ad000 —p 0000c000 08:02 33792348                   /usr/lib64/libnss_files-2.17.so
7f20ec9ad000-7f20ec9ae000 r–p 0000b000 08:02 33792348                   /usr/lib64/libnss_files-2.17.so
7f20ec9ae000-7f20ec9af000 rw-p 0000c000 08:02 33792348                   /usr/lib64/libnss_files-2.17.so
7f20ec9af000-7f20ec9b5000 rw-p 00000000 00:00 0
7f20ec9b5000-7f20ecb6d000 r-xp 00000000 08:02 33792330                   /usr/lib64/libc-2.17.so
7f20ecb6d000-7f20ecd6d000 —p 001b8000 08:02 33792330                   /usr/lib64/libc-2.17.so
7f20ecd6d000-7f20ecd71000 r–p 001b8000 08:02 33792330                   /usr/lib64/libc-2.17.so
7f20ecd71000-7f20ecd73000 rw-p 001bc000 08:02 33792330                   /usr/lib64/libc-2.17.so
7f20ecd73000-7f20ecd78000 rw-p 00000000 00:00 0
7f20ecd78000-7f20ecd7a000 r-xp 00000000 08:02 33792336                   /usr/lib64/libdl-2.17.so
7f20ecd7a000-7f20ecf7a000 —p 00002000 08:02 33792336                   /usr/lib64/libdl-2.17.so
7f20ecf7a000-7f20ecf7b000 r–p 00002000 08:02 33792336                   /usr/lib64/libdl-2.17.so
7f20ecf7b000-7f20ecf7c000 rw-p 00003000 08:02 33792336                   /usr/lib64/libdl-2.17.so
7f20ecf7c000-7f20ecfa1000 r-xp 00000000 08:02 33792448                   /usr/lib64/libtinfo.so.5.9
7f20ecfa1000-7f20ed1a1000 —p 00025000 08:02 33792448                   /usr/lib64/libtinfo.so.5.9
7f20ed1a1000-7f20ed1a5000 r–p 00025000 08:02 33792448                   /usr/lib64/libtinfo.so.5.9
7f20ed1a5000-7f20ed1a6000 rw-p 00029000 08:02 33792448                   /usr/lib64/libtinfo.so.5.9
7f20ed1a6000-7f20ed1c7000 r-xp 00000000 08:02 33792323                   /usr/lib64/ld-2.17.so
7f20ed3b0000-7f20ed3b3000 rw-p 00000000 00:00 0
7f20ed3bd000-7f20ed3be000 rw-p 00000000 00:00 0
7f20ed3be000-7f20ed3c5000 r–s 00000000 08:02 100902881                  /usr/lib64/gconv/gconv-modules.cache
7f20ed3c5000-7f20ed3c7000 rw-p 00000000 00:00 0
7f20ed3c7000-7f20ed3c8000 r–p 00021000 08:02 33792323                   /usr/lib64/ld-2.17.so
7f20ed3c8000-7f20ed3c9000 rw-p 00022000 08:02 33792323                   /usr/lib64/ld-2.17.so
7f20ed3c9000-7f20ed3ca000 rw-p 00000000 00:00 0
7fff5dfec000-7fff5e00d000 rw-p 00000000 00:00 0                          [stack]
7fff5e0f2000-7fff5e0f4000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
系统监控工具:      c/s服务模式
   glances命令:EPEL源
   glances [-bdehmnrsvyz1] [-B bind] [-c server] [-C conffile] [-p port] [-P password] [–password] [-
t refresh] [-f file] [-o output]
   内建命令:
a Sort processes automatically l Show/hide logs
c Sort processes by CPU% b Bytes or bits for network I/O
m Sort processes by MEM% w Delete warning logs
p Sort processes by name x Delete warning and critical logs
i Sort processes by I/O rate 1 Global CPU or per-CPU stats
d Show/hide disk I/O stats h Show/hide this help screen
f Show/hide file system stats t View network I/O as combination
n Show/hide network stats u View cumulative network I/O
s Show/hide sensors stats q Quit (Esc and Ctrl-C also work)
y Show/hide hddtemp stats
系统监控工具
  常用选项:
-b: 以Byte为单位显示网卡数据速率
-d: 关闭磁盘I/O模块
-f /path/to/somefile: 设定输入文件位置
-o {HTML|CSV}:输出格式
-m: 禁用mount模块
-n: 禁用网络模块
-t #: 延迟时间间隔
-1:每个CPU的相关数据单独显示
系统监控工具
  C/S模式下运行glances命令
  服务器模式:
glances -s -B IPADDR
IPADDR: 指明监听的本机哪个地址
  客户端模式:
glances -c IPADDR
IPADDR:要连入的服务器端地址
glances用法:
[root@centos6 ~]#glances -s -B 192.168.30.102
Glances server is running on 192.168.30.102:61209
[root@CENTOS7 ~]#glances -c 192.168.30.101
Connected to CENTOS7.localdomain (CentOS Linux 7.4.1708 64bit / Linux 3.10.0-693.el7.x86_64)             Uptime: 2:34:30
CPU  [       1.8%]   CPU       1.8%  nice:     0.0%   MEM     75.4%  active:     351M   SWAP      0.7%   LOAD    4-core
MEM  [||||  75.4%]   user:     1.1%  irq:      0.0%   total:  1.05G  inactive:   361M   total:   2.00G   1 min:    0.00
SWAP [       0.7%]   system:   0.6%  iowait:   0.0%   used:    810M  buffers:     36K   used:    14.0M   5 min:    0.03
                     idle:    98.3%  steal:    0.0%   free:    264M  cached:     161M   free:    1.99G   15 min:   0.05
NETWORK     Rx/s   Tx/s   TASKS 212 (417 thr), 1 run, 211 slp, 0 oth sorted automatically by memory_percent, flat view
eth0        144b   928b
eth1         5Kb     0b     CPU%  MEM%  VIRT   RES   PID USER        NI S     TIME+ IOR/s IOW/s Command
lo          38Kb   38Kb      0.0  12.0 1.70G  128M  1423 root         0 S   0:14.14     0     0 /usr/bin/gnome-shell
                             0.0   4.4 1.05G 47.0M  1615 root         0 S   0:00.85     0     0 /usr/libexec/evolution-c
DISK I/O     R/s    W/s      0.0   4.0 1.06G 43.5M  1815 root         0 S   0:00.33     0     0 /usr/libexec/evolution-c
dm-0           0      0      0.0   4.0 1.14G 43.4M  1802 root         0 S   0:00.30     0     0 /usr/libexec/evolution-c
dm-1           0      0      0.0   3.3 1024M 35.5M  1617 root         0 S   0:02.83     0     0 /usr/bin/gnome-software
sda1           0      0      1.2   1.7  232M 18.7M  4471 root         0 S   0:00.51     0     0 /usr/bin/python /bin/gla
sda2           0      0      0.0   1.6  549M 16.8M  1020 root         0 S   0:03.55     0     0 /usr/bin/python -Es /usr
sda3           0      0      5.8   1.5  221M 15.8M  4465 root         0 R   0:02.56     0     0 /usr/bin/python /bin/gla
sda4           0      0      0.0   1.4  303M 14.7M  1132 root         0 S   0:01.48     0     0 /usr/bin/X :0 -backgroun
sda5           0      0      0.0   1.4  111M 14.6M   796 root         0 S   0:00.31     0     0 /sbin/dhclient -d -q -sf
sda6           0      0      0.0   1.3  111M 14.3M   797 root         0 S   0:00.19     0     0 /sbin/dhclient -d -q -sf
sdb1           0      0
sdb2           0      0   Warning or critical alerts (one entry)
系统监控工具
  dstat命令:系统资源统计,代替vmstat,iostat
  dstat [-afv] [options..] [delay [count]]
-c: 显示cpu相关信息
-C #,#,…,total
-d: 显示disk相关信息
-D total,sda,sdb,…
-g:显示page相关统计数据
-m: 显示memory相关统计数据
-n: 显示network相关统计数据
-p: 显示process相关统计数据
-r: 显示io请求相关的统计数据
-s: 显示swapped相关的统计数据
–tcp
–udp
–unix
–raw
–socket
–ipc
–top-cpu:显示最占用CPU的进程
–top-io: 显示最占用io的进程
–top-mem: 显示最占用内存的进程
–top-latency: 显示延迟最大的进程
[root@CENTOS7 ~]#dstat 1       每秒刷新一次
You did not select any stats, using -cdngy by default.
—-total-cpu-usage—- -dsk/total- -net/total- —paging– —system–
usr sys idl wai hiq siq| read  writ| recv  send|  in   out | int   csw
  0   1  98   1   0   0| 116k   13k|   0     0 |  38B 2432B| 179   120
  0   0 100   0   0   0|   0     0 |1073B  842B|   0     0 | 156   135
  0   0 100   0   0   0|   0     0 |1038B  362B|   0     0 | 126   111
  0   1  99   0   0   0|   0     0 |1165B  362B|   0     0 | 239   171
[root@CENTOS7 ~]#dstat –top-cpu     查看CUP 使用率最大的程序
-most-expensive-
  cpu process
ping         0.1
ping          24
ping          24
ping          25
iotop
   iotop命令是一个用来监视磁盘I/O使用状况的top类工具iotop具有与top相似的UI,其
中包括PID、用户、I/O、进程等相关信息,可查看每个进程是如何使用IO
   iotop输出
第一行:Read和Write速率总计
第二行:实际的Read和Write速率
第三行:参数如下:
线程ID(按p切换为进程ID)
优先级
用户
磁盘读速率
磁盘写速率
swap交换百分比
IO等待所占的百分比
线程/进程命令
iotop常用参数
  -o, –only只显示正在产生I/O的进程或线程,除了传参,可以在运行过程中按o
生效
  -b, –batch非交互模式,一般用来记录日志
  -n NUM, –iter=NUM设置监测的次数,默认无限。在非交互模式下很有用
  -d SEC, –delay=SEC设置每次监测的间隔,默认1秒,接受非整形数据例如1.1
  -p PID, –pid=PID指定监测的进程/线程
  -u USER, –user=USER指定监测某个用户产生的I/O
  -P, –processes仅显示进程,默认iotop显示所有线程
  -a, –accumulated显示累积的I/O,而不是带宽
  -k, –kilobytes使用kB单位,而不是对人友好的单位。在非交互模式下,脚本
编程有用
iotop常用参数和快捷键
  -t, –time 加上时间戳,非交互非模式
  -q, –quiet 禁止头几行,非交互模式,有三种指定方式
   -q 只在第一次监测时显示列名
   -qq 永远不显示列名
   -qqq 永远不显示I/O汇总
  交互按键
left和right方向键:改变排序
r:反向排序
o:切换至选项–only
p:切换至–processes选项
a:切换至–accumulated选项
q:退出
i:改变线程的优先级
[root@CENTOS7 ~]#iotop
Total DISK READ :       0.00 B/s | Total DISK WRITE :       0.00 B/s
Actual DISK READ:       0.00 B/s | Actual DISK WRITE:       0.00 B/s
   PID  PRIO  USER     DISK READ  DISK WRITE  SWAPIN     IO>    COMMAND
  3024 be/4 root        0.00 B/s    0.00 B/s  0.00 %  0.04 % [kworker/3:0]
  1536 be/4 root        0.00 B/s    0.00 B/s  0.00 %  0.00 % goa-identity-service
进程管理工具
   kill命令:
向进程发送控制信号,以实现对进程管理,每个信号对应一个数字,信号名称以SIG开头
(可省略),不区分大小写
显示当前系统可用信号: kill –l,trap -l
常用信号:man 7 signal
1) SIGHUP: 无须关闭进程而让其重读配置文件
2) SIGINT: 中止正在运行的进程;相当于Ctrl+c
3) SIGQUIT:相当于ctrl+\        相当于quit
9) SIGKILL: 强制杀死正在运行的进程
15) SIGTERM:终止正在运行的进程
18) SIGCONT:继续运行
19) SIGSTOP:后台休眠
指定信号的方法:
(1) 信号的数字标识:1, 2, 9
(2) 信号完整名称:SIGHUP  (3) 信号的简写名称:HUP
[root@CENTOS7 ~]#ss -ntl
State      Recv-Q Send-Q               Local Address:Port                              Peer Address:Port
LISTEN     0      128                              *:111                                          *:*
LISTEN     0      128                              *:22                                           *:*
LISTEN     0      128                      127.0.0.1:631                                          *:*
LISTEN     0      100                      127.0.0.1:25                                           *:*
LISTEN     0      128                             :::111                                         :::*
LISTEN     0      128                             :::80                                          :::*
LISTEN     0      128                             :::22                                          :::*
LISTEN     0      128                            ::1:631                                         :::*
LISTEN     0      100                            ::1:25                                          :::*
[root@CENTOS7 ~]#ps aux | grep httpd
root       2127  0.0  0.2 226240  3072 ?        Ss   09:10   0:01 /usr/sbin/httpd -DFOREGROUND
apache     2129  0.0  0.2 228324  2380 ?        S    09:10   0:00 /usr/sbin/httpd -DFOREGROUND
apache     2130  0.0  0.2 228324  2380 ?        S    09:10   0:00 /usr/sbin/httpd -DFOREGROUND
apache     2131  0.0  0.2 228324  2380 ?        S    09:10   0:00 /usr/sbin/httpd -DFOREGROUND
apache     2132  0.0  0.2 228324  2380 ?        S    09:10   0:00 /usr/sbin/httpd -DFOREGROUND
apache     2133  0.0  0.2 228324  2380 ?        S    09:10   0:00 /usr/sbin/httpd -DFOREGROUND
root       4958  0.0  0.0 112664   972 pts/0    S+   11:57   0:00 grep –color=auto httpd
[root@CENTOS7 ~]#vim /etc/httpd/conf/httpd.conf
User daemon
Group apache
[root@CENTOS7 ~]#ps aux | grep httpd
root       2127  0.0  0.2 226240  3072 ?        Ss   09:10   0:02 /usr/sbin/httpd -DFOREGROUND
apache     2129  0.0  0.2 228324  2380 ?        S    09:10   0:00 /usr/sbin/httpd -DFOREGROUND
apache     2130  0.0  0.2 228324  2380 ?        S    09:10   0:00 /usr/sbin/httpd -DFOREGROUND
apache     2131  0.0  0.2 228324  2380 ?        S    09:10   0:00 /usr/sbin/httpd -DFOREGROUND
apache     2132  0.0  0.2 228324  2380 ?        S    09:10   0:00 /usr/sbin/httpd -DFOREGROUND
apache     2133  0.0  0.2 228324  2380 ?        S    09:10   0:00 /usr/sbin/httpd -DFOREGROUND
root       5529  0.0  0.0 112664   968 pts/0    S+   12:39   0:00 grep –color=auto httpd
[root@CENTOS7 ~]#systemctl restart httpd
[root@CENTOS7 ~]#ps aux | grep httpd
root       5556  0.9  0.4 226240  5132 ?        Ss   12:40   0:00 /usr/sbin/httpd -DFOREGROUND
daemon     5558  0.1  0.2 228324  3152 ?        S    12:40   0:00 /usr/sbin/httpd -DFOREGROUND
daemon     5559  0.0  0.2 228324  3152 ?        S    12:40   0:00 /usr/sbin/httpd -DFOREGROUND
daemon     5560  0.0  0.2 228324  3152 ?        S    12:40   0:00 /usr/sbin/httpd -DFOREGROUND
daemon     5561  0.0  0.2 228324  3152 ?        S    12:40   0:00 /usr/sbin/httpd -DFOREGROUND
daemon     5562  0.0  0.2 228324  3152 ?        S    12:40   0:00 /usr/sbin/httpd -DFOREGROUND
root       5564  0.0  0.0 112660   972 pts/0    R+   12:40   0:00 grep –color=auto httpd
[root@CENTOS7 ~]#vim /etc/httpd/conf/httpd.conf
User apache
Group apache
[root@CENTOS7 ~]#ps aux | grep httpd
root       5556  0.2  0.4 226240  5132 ?        Ss   12:40   0:00 /usr/sbin/httpd -DFOREGROUND
daemon     5558  0.0  0.2 228324  3152 ?        S    12:40   0:00 /usr/sbin/httpd -DFOREGROUND
daemon     5559  0.0  0.2 228324  3152 ?        S    12:40   0:00 /usr/sbin/httpd -DFOREGROUND
daemon     5560  0.0  0.2 228324  3152 ?        S    12:40   0:00 /usr/sbin/httpd -DFOREGROUND
daemon     5561  0.0  0.2 228324  3152 ?        S    12:40   0:00 /usr/sbin/httpd -DFOREGROUND
daemon     5562  0.0  0.2 228324  3152 ?        S    12:40   0:00 /usr/sbin/httpd -DFOREGROUND
root       5586  0.0  0.0 112660   972 pts/0    R+   12:42   0:00 grep –color=auto httpd
[root@CENTOS7 ~]#kill -1 5556
[root@CENTOS7 ~]#ps aux | grep httpd
root       5556  0.1  0.4 226236  5100 ?        Ss   12:40   0:00 /usr/sbin/httpd -DFOREGROUND
root       5589  0.0  0.0 112660   968 pts/0    S+   12:42   0:00 grep –color=auto httpd
[root@CENTOS7 ~]#ps aux | grep httpd
root       5556  0.1  0.4 226240  5160 ?        Ss   12:40   0:00 /usr/sbin/httpd -DFOREGROUND
apache     5591  0.0  0.2 228324  3132 ?        S    12:43   0:00 /usr/sbin/httpd -DFOREGROUND
apache     5592  0.0  0.2 228324  3128 ?        S    12:43   0:00 /usr/sbin/httpd -DFOREGROUND
apache     5593  0.0  0.2 228324  3148 ?        S    12:43   0:00 /usr/sbin/httpd -DFOREGROUND
apache     5594  0.0  0.2 228324  3148 ?        S    12:43   0:00 /usr/sbin/httpd -DFOREGROUND
apache     5595  0.0  0.2 228324  3148 ?        S    12:43   0:00 /usr/sbin/httpd -DFOREGROUND
root       5597  0.0  0.0 112664   972 pts/0    S+   12:43   0:00 grep –color=auto httpd
用kill -1 pid 使进程重读配置文件时,有的进程好用,有的不好用,父进程pid不变,旗下的子进程pid发生改变。
[root@CENTOS7 ~]#pidof ping
5657
[root@CENTOS7 ~]#kill -2 5657       -2 相当于Ctrl + c
[root@CENTOS7 ~]#pidof bc
5735
[root@CENTOS7 ~]#kill -3 5735       -3 相当于quit
[root@CENTOS7 ~]#pidof ping
5760
[root@CENTOS7 ~]#kill -15 5760       -15 相当于正常退出
[root@centos6 ~]#ps aux | grep minget*       mingetty是登录界面进程,是再生进程
root       2932  0.0  0.0   4068   544 tty2     Ss+  08:42   0:00 /sbin/mingetty /dev/tty2
root       2934  0.0  0.0   4068   540 tty3     Ss+  08:42   0:00 /sbin/mingetty /dev/tty3
root       2936  0.0  0.0   4068   540 tty4     Ss+  08:42   0:00 /sbin/mingetty /dev/tty4
root       2938  0.0  0.0   4068   544 tty5     Ss+  08:42   0:00 /sbin/mingetty /dev/tty5
root       2940  0.0  0.0   4068   544 tty6     Ss+  08:42   0:00 /sbin/mingetty /dev/tty6
root       4416  0.0  0.0 103336   972 pts/0    S+   12:43   0:00 grep –color=auto minget*
[root@centos6 ~]#kill -15 2932       这种进程杀不死,以为它是再生进程
[root@centos6 ~]#ps aux | grep minget*
root       2934  0.0  0.0   4068   540 tty3     Ss+  08:42   0:00 /sbin/mingetty /dev/tty3
root       2936  0.0  0.0   4068   540 tty4     Ss+  08:42   0:00 /sbin/mingetty /dev/tty4
root       2938  0.0  0.0   4068   544 tty5     Ss+  08:42   0:00 /sbin/mingetty /dev/tty5
root       2940  0.0  0.0   4068   544 tty6     Ss+  08:42   0:00 /sbin/mingetty /dev/tty6
root       4418  1.0  0.0   4068   536 tty2     Ss+  12:44   0:00 /sbin/mingetty /dev/tty2
root       4420  0.0  0.0 103336   972 pts/0    S+   12:44   0:00 grep –color=auto minget*
[root@centos6 ~]#kill -9 1      虽然杀不死1 进程,但是已经对1进程造成了损坏,这是再生进程就可以杀死。破坏符进程,到时再生进程不可再生
[root@centos6 ~]#kill -15 2932
[root@centos6 ~]#ps aux | grep minget*
root       2934  0.0  0.0   4068   540 tty3     Ss+  08:42   0:00 /sbin/mingetty /dev/tty3
root       2936  0.0  0.0   4068   540 tty4     Ss+  08:42   0:00 /sbin/mingetty /dev/tty4
root       2938  0.0  0.0   4068   544 tty5     Ss+  08:42   0:00 /sbin/mingetty /dev/tty5
root       2940  0.0  0.0   4068   544 tty6     Ss+  08:42   0:00 /sbin/mingetty /dev/tty6
root       4420  0.0  0.0 103336   972 pts/0    S+   12:44   0:00 grep –color=auto minget*
进程管理工具
  按PID:kill [-SIGNAL] pid …
kill –n SIGNAL pid;kill –s SIGNAL pid
  按名称:killall [-SIGNAL] comm…
  按模式:pkill [options] pattern
-SIGNAL
-u uid: effective user,生效者
-U uid: real user,真正发起运行命令者
-t terminal: 与指定终端相关的进程
-l: 显示进程名(pgrep可用)
-a: 显示完整格式的进程名(pgrep可用)
-P pid: 显示指定进程的子进程
kill -number pid
killall cmd
pkill
[root@CENTOS7 ~]#pgrep -at pts/1
2049 -bash
2134 su –
2138 -bash
6030 sleep 123
[root@CENTOS7 ~]#pkill -9 -t pts/1    强制杀掉pts/1上的所有进程
作业管理
  Linux的作业控制
前台作业:通过终端启动,且启动后一直占据终端;
后台作业:可通过终端启动,但启动后即转入后台运行(释放终端)
  让作业运行于后台
(1) 运行中的作业:  Ctrl+z
(2) 尚未启动的作业: COMMAND &
  后台作业虽然被送往后台运行,但其依然与终端相关;退出终端,将关闭后台作业。如果希望
送往后台后,剥离与终端的关系
nohup COMMAND &>/dev/null &
screen;COMMAND
  查看当前终端所有作业:jobs
  作业控制:
fg [[%]JOB_NUM]:把指定的后台作业调回前台
bg [[%]JOB_NUM]:让送往后台的作业在后台继续运行
kill [%JOB_NUM]: 终止指定的作业
ping 172.18.0.1 &    让ping后台运行,信息仍在终端上显示,但是可以执行别的命令。
输入jobs查看后台运行的编号,fg +编号 恢复到前台
一个前天运行的命令ping172.18.0.1想要后台运行按Ctrl+z。
[root@CENTOS7 ~]#ping 127.0.0.2
PING 127.0.0.2 (127.0.0.2) 56(84) bytes of data.
64 bytes from 127.0.0.2: icmp_seq=1 ttl=64 time=0.024 ms
64 bytes from 127.0.0.2: icmp_seq=2 ttl=64 time=0.080 ms
64 bytes from 127.0.0.2: icmp_seq=3 ttl=64 time=0.077 ms
64 bytes from 127.0.0.2: icmp_seq=4 ttl=64 time=0.080 ms
^Z
[1]+  Stopped                 ping 127.0.0.2        Ctrl+z     后台停止运行。
bg 1   开始后台运行
ping 172.18.0.1 &
pidof ping
7421
kill -19 7421或者 killall -19 ping
jobs     只在当前终端当前bash下好用
[root@CENTOS7 ~]#jobs
[1]+  Stopped                 ping 127.0.0.1
后台继续运行 bg 1 或者 killall -18 ping
kill %jobsnumber 停止后台程序
后台运行的程序任然与终端有关,jobs命令只在程序运行的终端有效,在别的终端无法查看。
后台执行的命令一但断网也会停止执行,可以在screen中运行程序ping172.20.0.1这样即使断网,在网络恢复后可以screen -r继续这个程序
后台执行的命令一但断网也会停止执行,也可以用nohup ping172.20.0.1 & 即使断网也会继续执行,将执行结果保存在 nohup.out中
断网后,ping命令的进程树会自动切换到init(centos6)或者systemd(centos7)的子进程
并行运行
  同时运行多个进程,提高效率
  方法1
vi all.sh
f1.sh&
f2.sh&
f3.sh&
  方法2
(f1.sh&);(f2.sh&);(f3.sh&)
  方法3
{ f1.sh& f2.sh& f3.sh& }
多任务并行运行:
[root@centos6 ~]#vim morejobs.sh
#!/bin/bash
#
#********************************************************************
#Author:                wangxiaochun
#QQ:                    29308620
#Date:                  2018-05-05
#FileName:             morejobs.sh
#URL:                   http://www.magedu.com
#Description:          The test script
#Copyright (C):         2018 All rights reserved
#******************************************************************
ping 127.1 &
ping 127.2 &
ping 127.3 &
~
(ping 127.1 &) ; (ping 127.2 &) ; (ping 127.3 &)
{ ping 127.1 & ping 127.2 & ping 127.3 & }
任务计划
  Linux任务计划、周期性任务执行
  未来的某时间点执行一次任务
at
batch:系统自行选择空闲时间去执行此处指定的任务
  周期性运行某任务
cron
at任务
   包:at
   at命令:at [option] TIME
   常用选项:
-V 显示版本信息:
-l: 列出指定队列中等待运行的作业;相当于atq
-d: 删除指定的作业;相当于atrm
-c: 查看具体作业任务
-f /path/from/somefile:从指定的文件中读取任务
-m:当任务被完成之后,将给用户发送邮件,即使没有标准输出
   注意:作业执行命令的结果中的标准输出和错误以邮件通知给相关用户
   TIME:定义出什么时候进行 at 这项任务的时间
HH:MM [YYYY-mm-dd]
noon, midnight, teatime(4pm)
tomorrow
now+#{minutes,hours,days, OR weeks}
[root@CENTOS7 ~]#systemctl status atd       查看atd服务是否开启
● atd.service – Job spooling tools
   Loaded: loaded (/usr/lib/systemd/system/atd.service; enabled; vendor preset: enabled)
   Active: active (running) since Sat 2018-05-05 09:01:10 CST; 6h ago
 Main PID: 1031 (atd)
   CGroup: /system.slice/atd.service
           └─1031 /usr/sbin/atd -f
May 05 09:01:10 CENTOS7.localdomain systemd[1]: Started Job spooling tools.
May 05 09:01:10 CENTOS7.localdomain systemd[1]: Starting Job spooling tools…
[root@centos6 ~]#service atd status
atd (pid  2893) is running…
[root@centos6 ~]#at -V
at version 3.1.10
[root@CENTOS7 ~]#at -V
at version 3.1.13
[root@CENTOS7 ~]#vim /etc/chrony.conf   自动同步时间,但是不能和服务器的时间相差太多事同步。
# Use public servers from the pool.ntp.org project.
# Please consider joining the pool (http://www.pool.ntp.org/join.html).
server 172.20.0.1 iburst
server 0.centos.pool.ntp.org iburst
server 1.centos.pool.ntp.org iburst
server 2.centos.pool.ntp.org iburst
server 3.centos.pool.ntp.org iburst
ntpdate 172.20.0.1
systemctl start chronyd
systemctl enable chronyd
[root@CENTOS7 ~]#systemctl status chronyd
● chronyd.service – NTP client/server
   Loaded: loaded (/usr/lib/systemd/system/chronyd.service; enabled; vendor preset: enabled)
   Active: active (running) since Sat 2018-05-05 15:56:40 CST; 3min 36s ago
     Docs: man:chronyd(8)
           man:chrony.conf(5)
  Process: 9271 ExecStartPost=/usr/libexec/chrony-helper update-daemon (code=exited, status=0/SUCCESS)
  Process: 9267 ExecStart=/usr/sbin/chronyd $OPTIONS (code=exited, status=0/SUCCESS)
 Main PID: 9269 (chronyd)
   CGroup: /system.slice/chronyd.service
           └─9269 /usr/sbin/chronyd
May 05 15:56:40 CENTOS7.localdomain systemd[1]: Starting NTP client/server…
May 05 15:56:40 CENTOS7.localdomain chronyd[9269]: chronyd version 3.1 starting (+CMDMON +NTP +REFCLOCK +RTC +PRIVDROP +…EBUG)
May 05 15:56:40 CENTOS7.localdomain systemd[1]: Started NTP client/server.
May 05 15:56:57 CENTOS7.localdomain chronyd[9269]: Selected source 172.20.0.1
May 05 15:56:57 CENTOS7.localdomain chronyd[9269]: System clock wrong by 88.078821 seconds, adjustment started
May 05 15:58:25 CENTOS7.localdomain chronyd[9269]: System clock was stepped by 88.078821 seconds
May 05 15:58:26 CENTOS7.localdomain chronyd[9269]: Source 120.25.108.11 replaced with 193.228.143.12
Hint: Some lines were ellipsized, use -l to show in full.
[root@centos6 ~]#ntpdate 172.20.0.1
 5 May 16:04:29 ntpdate[6818]: step time server 172.20.0.1 offset 1207.025516 sec
[root@centos6 ~]#vim /etc/ntp.conf
server 172.20.0.1 iburst
[root@centos6 ~]#service ntpd start
Starting ntpd:                                             [  OK  ]
[root@centos6 ~]#chkconfig –list                  查看系统中开启的服务
NetworkManager 0:off 1:off 2:on 3:on 4:on 5:on 6:off
abrt-ccpp       0:off 1:off 2:off 3:on 4:off 5:on 6:off
abrtd           0:off 1:off 2:off 3:on 4:off 5:on 6:off
[root@centos6 ~]#cat /etc/inittab
#   0 – halt (Do NOT set initdefault to this)
#   1 – Single user mode
#   2 – Multiuser, without NFS (The same as 3, if you do not have networking)
#   3 – Full multiuser mode
#   4 – unused
#   5 – X11
#   6 – reboot (Do NOT set initdefault to this)
[root@centos6 ~]#chkconfig ntpd on        开机自动启动
[root@centos6 ~]#service ntpd status
ntpd (pid  6854) is running…
at 一次性计划任务的用法
[root@CENTOS7 d2]#at 17:00
at> rm -rf /data/d1/d2/d3
at> touch f1 /data/d1/d2
at> <EOT>
job 2 at Sat May  5 17:00:00 2018
[root@CENTOS7 d2]#at -l       查看有没有计划任务
2 Sat May  5 17:00:00 2018 a root
[root@CENTOS7 ~]#at -c 2      查看这个计划具体内容
#!/bin/sh
# atrun uid=0 gid=0
# mail wang 0
rm -rf /data/d1/d2/d3
touch f1 /data/d1/d2
marcinDELIMITER70628090
[root@CENTOS7 ~]#ls /var/spool/at/a000020183f51c     这个计划存放在磁盘上的位置。
/var/spool/at/a000020183f51c
at时间格式
  HH:MM 02:00
在今日的 HH:MM 进行,若该时刻已过,则明天此时执行任务
  HH:MM YYYY-MM-DD 02:00 2016-09-20
规定在某年某月的某一天的特殊时刻进行该项任务
  HH:MM[am|pm] [Month] [Date]
04pm March 17
17:20 tomorrow
  HH:MM[am|pm] + number [minutes|hours|days|weeks]
在某个时间点再加几个时间后才进行该项任务
now + 5 minutes
02pm + 3 days
[root@CENTOS7 ~]#at now + 15minutes
at> touch ffffffffffffff /data
at> <EOT>
job 3 at Sat May  5 16:50:00 2018
[root@CENTOS7 ~]#at -l
2 Sat May  5 17:00:00 2018 a root
3 Sat May  5 16:50:00 2018 a root
[root@CENTOS7 ~]#at -c 3
touch ffffffffffffff /data
删除计划任务
at -d 2
cat > f1
reboot
echo 123456789
at -f f1 17:50 + 1days
at now + 25hours < f1
如果计划任务中的命令有标准输出,并不会在终端上显示,会以邮件的方式发送给用户。
在脚本中将标准输出都从定向到/dev/null
如果想确定计划任务执行没执行,可以at -m -f f1 17:50 + 1days  这样即使计划中没有标准输出也会给
用户发一个空邮件在告诉用户计划已经执行。
[root@CENTOS7 ~]#echo wall lushen will be died | at now + 1minutes
job 4 at Sat May  5 16:56:00 2018
[root@CENTOS7 ~]#
Broadcast message from root@CENTOS7.localdomain (Sat May  5 16:56:00 2018):
lushen will be died
at任务
?执行方式:
1)交互式 2)输入重定向 3)at –f 文件
?依赖与atd服务,需要启动才能实现at任务
?at队列存放在/var/spool/at目录中
?/etc/at.{allow,deny}控制用户是否能执行at任务
白名单:/etc/at.allow 默认不存在,只有该文件中的用户才能执行at命令
黑名单:/etc/at.deny 默认存在,拒绝该文件中用户执行at命令,而没有在
at.deny 文件中的使用者则可执行
如果两个文件都不存在,只有 root 可以执行 at 命令
[root@CENTOS7 ~]#cat /etc/at.deny    黑名单
默认下没有白名单需要手工创建
将用户加入黑名单中这个用户就无法创建计划任务,但是不在黑名单中的用户不受影响,如果将用户同时放到白名单和黑名单中,白名单生效
而且除了白名单中的用户,其他用户都不可以创建计划任务。如果黑白名单有没有只有root能执行计划任务
在脚本中编写at任务
#! /bin/bash
at 18:00 << 123
halt
123
周期性任务计划cron
  周期性任务计划:cron
  相关的程序包:
cronie: 主程序包,提供crond守护进程及相关辅助工具
cronie-anacron:cronie的补充程序,用于监控cronie任务执行状况,如
cronie中的任务在过去该运行的时间点未能正常运行,则anacron会随后启动一次
此任务
crontabs:包含CentOS提供系统维护任务
[root@CENTOS7 ~]#cat /etc/crontab
SHELL=/bin/bash
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
 0  2   *   *  1-5  wang  cp -p /etc /data/ > /dev/null     周一到周五每天晚上2天备份文件/etc到/data下
 0  2  1,10,20 * 0,6  wang tar -Jcpf /data/etc.tar.xz /etc/ > /dev/null
这里1,10,20 和 0,6 是或者的意思,如果想完成并且的关系
需要些脚本判断今天是不是周六周日如果是则打包,如果不是则不打包。
*/10 2 * * * root wall hello     每10分钟root发送一次广播内容是hello
@reboot root rm -rf /data/*     重启的时候已root的身份清空/data,只要关机启动就算一次重启
计划任务
?确保crond守护处于运行状态:
CentOS 7:
systemctl status crond
CentOS 6:
service crond status
?计划周期性执行的任务提交给crond,到指定时间会自动运行
系统cron任务:系统维护作业
/etc/crontab
用户cron任务:
crontab命令
?日志:/var/log/cron
计划任务
  系统cron任务:/etc/crontab
  注释行以 # 开头
  详情参见 man 5 crontab
# 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
  例如:晚上9点10分运行echo命令
10 21 * * *  centos /bin/echo “Howdy!”
计划任务
  时间表示法:
  (1) 特定值
给定时间点有效取值范围内的值
  (2) *
给定时间点上有效取值范围内的所有值
表示“每…”
  (3) 离散取值
#,#,#
  (4) 连续取值
#-#
  (5) 在指定时间范围上,定义步长
/#: #即为步长
时间格式
  @reboot Run once after reboot
  @yearly 0 0 1 1 *
  @annually  0 0 1 1 *
  @monthly  0 0 1 * *
  @weekly 0 0 * * 0
  @daily  0 0 * * *
  @hourly 0 * * * *
  示例:每3小时echo和wall命令
0 */3 * * * centos /bin/echo “howdy”;/usr/bin/wall “welcome to Magedu!”  发邮件
[wang@CENTOS7 ~]$crontab -e
 * * * * * wall lu shen is a shabi
~
[wang@CENTOS7 ~]$
Broadcast message from wang@CENTOS7.localdomain (Sat May  5 19:11:01 2018):
lu shen is a shabi
[wang@CENTOS7 ~]$vim /var/spool/cron/wang
/var/spool/cron/wang” [Permission Denied]
wang用户无法直接编辑这个文件,但是可以使用命令crontab -e 来编辑这个文件
因为 crontab 命令有 sgid 。
[wang@CENTOS7 ~]$crontab -l -u root    只有root能够运行
must be privileged(特权) to use -u
计划任务
  系统的计划任务:
/etc/crontab
/etc/cron.d/ 配置文件
/etc/cron.hourly/ 脚本
/etc/cron.daily/ 脚本
/etc/cron.weekly/  脚本
/etc/cron.monthly/  脚本
用户计划任务
  crontab命令定义
每个用户都有专用的cron任务文件:  /var/spool/cron/USERNAME
  crontab命令:
crontab [-u user] [-l | -r | -e] [-i]
-l: 列出所有任务
-e: 编辑任务
-r: 移除所有任务
-i:同-r一同使用,以交互式模式移除指定任务
-u user: 仅root可运行,指定用户管理cron任务
   控制用户执行计划任务:
/etc/cron.{allow,deny}   与at 文件的黑白名单一样,如果是在加入黑名单之前创建的计划任务可以继续执行,但是无法再创建计划任务。
at和crontab
  一次性作业使用 at
  重复性作业使用crontab
Create            at  time   crontab -e
List  at -l crontab -l
Details  at -c jobnum N/A
Remove  at -d jobnum crontab -r
Edit (编辑修改)   N/A crontab -e
  没有被重定向的输出会被邮寄给用户
  根用户能够修改其它用户的作业
每十分钟检查一下磁盘利用率,大于 80 报警。
[root@CENTOS7 ~]#df | sed -r -n ‘s@^/dev/sd.*[ ]+([[:digit:]]{,3})%.*@\1@p’
10
1
16
[root@CENTOS7 ~]#df | grep /dev/sd | sed -r ‘s@.*[ ]+([0-9]{,3})%.*@\1@’ | sort -nr | head -n 1
16
[root@CENTOS7 ~]#df -i | grep /dev/sd | sed -r ‘s@.*[ ]+([0-9]{,3})%.*@\1@’ | sort -nr | head -n 1
1
1
1
耗光节点编号 echo f{1..523959} | xargs -n 100 touch
[root@CENTOS7 ~]#vim diskspace.sh
#!/bin/bash
#
#********************************************************************
#Author:                wangxiaochun
#QQ:                    29308620
#Date:                  2018-05-05
#FileName:             diskspace.sh
#URL:                   http://www.magedu.com
#Description:          The test script
#Copyright (C):         2018 All rights reserved
#********************************************************************
a=`df | grep /dev/sd | sed -r ‘s@.*[ ]+([0-9]{,3})%.*@\1@’ | sort -nr | head -n 1`
b=`df -i | grep /dev/sd | sed -r ‘s@.*[ ]+([0-9]{,3})%.*@\1@’ | sort -nr | head -n 1`
[ “$a” -ge 80 -o “$b” -ge 80 ] &&echo  “your disk will be full” ||echo  “your disk is ok”
[root@CENTOS7 ~]#vim /etc/crontab
SHELL=/bin/bash
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
@reboot root reboot                                 一但重启则无限循环重启
解决无限重启办法:
centos7
vim /sysroot/etc/crontab
@reboot root reboot
boot menu kernel e
linux16 加 rd.break
ctrl+x
mount -o remount,rw /sysroot
vim /sysroot/etc/crontab
centos6
a
加 空格 1 enter
vim /sysroot/etc/crontab
init 5
在一个目录/data/下放上多个脚本比如
f2.sh
f1.sh
run-paths /data
就会把 /data中的脚本全部运行
anacron系统
  运行计算机关机时cron不运行的任务,CentOS6以后版本取消anacron服务,由
crond服务管理
  对笔记本电脑、台式机、工作站、偶尔要关机的服务器及其它不一直开机的系统
很重要对很有用
  配置文件:/etc/anacrontab,负责执行/etc/ cron.daily /etc/cron.weekly
/etc/cron.monthly中系统任务。
  字段1:如果在这些日子里没有运行这些任务……
  字段2:在重新引导后等待这么多分钟后运行它
  字段3:任务识别器,在日志文件中标识
  字段4:要执行的任务
  由/etc/cron.hourly/0anacron执行
  当执行任务时,更新/var/spool/anacron/cron.daily 文件的时间戳
[root@CENTOS7 ~]#cat /etc/anacrontab
# /etc/anacrontab: configuration file for anacron
# See anacron(8) and anacrontab(5) for details.
SHELL=/bin/sh
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# the maximal random delay added to the base delay of the jobs
RANDOM_DELAY=45
# the jobs will be started during the following hours only
START_HOURS_RANGE=3-22
#period in days   delay in minutes   job-identifier   command
1 5 cron.daily nice run-parts /etc/cron.daily
7 25 cron.weekly nice run-parts /etc/cron.weekly
@monthly 45 cron.monthly nice run-parts /etc/cron.monthly
周期性任务计划cron
  周期性任务计划:cron
  相关的程序包:
cronie: 主程序包,提供crond守护进程及相关辅助工具
cronie-anacron:cronie的补充程序,用于监控cronie任务执行状况,如
cronie中的任务在过去该运行的时间点未能正常运行,则anacron会随后启动一次
此任务
crontabs:包含CentOS提供系统维护任务
[root@CENTOS7 ~]#ll /etc/cron.*                  系统自带的计划任务
-rw——-. 1 root root  0 Aug  3  2017 /etc/cron.deny
/etc/cron.d:
total 12
-rw-r–r–. 1 root root 128 Aug  3  2017 0hourly
-rw-r–r–. 1 root root 108 Jun 13  2017 raid-check
-rw——-. 1 root root 235 Aug  3  2017 sysstat
/etc/cron.daily:
total 12
-rwx——. 1 root root 219 Aug  2  2017 logrotate     生成一个滚动日志目录
-rwxr-xr-x. 1 root root 618 Mar 18  2014 man-db.cron     生成whatis数据库
-rwx——. 1 root root 208 Nov  5  2016 mlocate         创建locate索引
/etc/cron.hourly:
total 8
-rwxr-xr-x. 1 root root 392 Aug  3  2017 0anacron
-rwxr-xr-x. 1 root root 191 Aug  4  2017 mcelog.cron
/etc/cron.monthly:
total 0
/etc/cron.weekly:
total 0
管理临时文件
  CentOS6使用/etc/cron.daily/tmpwatch定时清除临时文件
  CentOS7使用systemd-tmpfiles-setup服务实现
  配置文件:
  /etc/tmpfiles.d/*.conf
  /run/tmpfiles.d/*.conf
  /usr/lib/tmpfiles/*.conf
  /usr/lib/tmpfiles.d/tmp.conf
  d /tmp 1777 root root 10d
  d /var/tmp 1777 root root 30d
  命令:
  systemd-tmpfiles –clean|remove|create configfile
[root@centos6 ~]#ll /etc/cron.daily
total 28
-rwx——. 1 root root  118 Mar 22  2017 cups
-rwx——. 1 root root  180 Jul 10  2003 logrotate
-rwx——. 1 root root  927 Mar 22  2017 makewhatis.cron
-rwx——. 1 root root  189 Jan 26  2015 mlocate.cron
-rwxr-xr-x. 1 root root 2126 Jul 19  2013 prelink
-rwxr-xr-x. 1 root root  563 Nov 23  2013 readahead.cron
-rwxr-xr-x. 1 root root  433 Nov  7  2015 tmpwatch       每天清除垃圾临时文件
[root@centos6 ~]#cat /etc/cron.daily/tmpwatch
#! /bin/sh
flags=-umc
/usr/sbin/tmpwatch “$flags” -x /tmp/.X11-unix -x /tmp/.XIM-unix \
-x /tmp/.font-unix -x /tmp/.ICE-unix -x /tmp/.Test-unix \
-X ‘/tmp/hsperfdata_*’ -X ‘/tmp/.hdb*lock’ -X ‘/tmp/.sapstartsrv*.log’ \
-X ‘/tmp/pymp-*’ 10d /tmp     超过10天删除
/usr/sbin/tmpwatch “$flags” 30d /var/tmp     超过30天删除
for d in /var/{cache/man,catman}/{cat?,X11R6/cat?,local/cat?}; do
    if [ -d “$d” ]; then
/usr/sbin/tmpwatch “$flags” -f 30d “$d”
    fi
done
计划任务
  注意:运行结果的标准输出和错误以邮件通知给相关用户
(1) COMMAND > /dev/null
(2) COMMAND &> /dev/null
  对于cron任务来讲,%有特殊用途;如果在命令中要使用%,则需要转义,将%
放置于单引号中,则可不用转义
在计划任务中放入 touch /data/`date +%f`.log
tail -f /var/spoll/cron 跟中日志文件发现放入中的命令%f不见了因为在计划任务中%有特殊用途。
所以这样写不行,可以将这个命令放入脚本中。在放入计划任务中执行。
计划任务
  思考:
  (1) 如何在秒级别运行任务?
* * * * * for min in 0 1 2; do echo “hi”; sleep 20; done
  (2) 如何实现每7分钟运行一次任务?   sleep 7m
  sleep命令:
sleep NUMBER[SUFFIX]…
SUFFIX:
s: 秒, 默认
m: 分
h: 小时
d: 天
usleep   微秒  1秒=1000000微秒
vim f1.sh
cmd 0
sleep 20
cmd 20
sleep 20
cmd 40
* * * * * f1.sh      每20秒执行一次cmd命令
vim f1.sh
cmd
sleep 20
f1.sh                自己调用自己变成死循环
流程控制
  过程式编程语言:
顺序执行
选择执行
循环执行
条件选择if语句
  选择执行:
  注意:if语句可嵌套
  单分支
if 判断条件;then
条件为真的分支代码
fi
  双分支
if 判断条件; then
条件为真的分支代码
else
条件为假的分支代码
fi
if 语句
  多分支
if 判断条件 1 ; then
条件为真的分支代码
elif 判断条件 2 ; then
条件为真的分支代码
elif 判断条件 3 ; then
条件为真的分支代码
else
以上条件都为假的分支代码
fi
  逐条件进行判断,第一次遇为“真”条件时,执行其分支,而后结束整个if语句
If示例
  根据命令的退出状态来执行命令
if ping -c1 -W2 station1 &> /dev/null; then
echo ‘Station1 is UP’
elif grep “station1” ~/maintenance.txt &> /dev/null
then
echo ‘Station1 is undergoing maintenance‘
else echo ‘Station1 is unexpectedly DOWN!’ exit 1
fi
用if语句判断年龄
[root@CENTOS7 ~]#vim test_age.sh
#!/bin/bash
#
#********************************************************************
#Author:                wangxiaochun
#QQ:                    29308620
#Date:                  2018-05-06
#FileName:             test_age.sh
#URL:                   http://www.magedu.com
#Description:          The test script
#Copyright (C):         2018 All rights reserved
#********************************************************************
read -p “please input your age :” AGE
[[ “$AGE” =~ ^[0-9]+$ ]] || { echo “your input is not a number” ; exit ; }
if [ “$AGE” -lt 18 ] ; then
        echo “good good study,day day up”
elif [ “$AGE” -ge 18 -a “$AGE” -lt 60 ] ; then
        echo “good good work”
elif [ “$AGE” -ge 60 -a “$AGE” -le 150 ] ; then
        echo “have a good time”
else
        echo “you are not from earth”
fi
如果条件(组合)过多就不适合用if
比如判断yes,no或者
1,2,3 cmd
4,5,6 cmd
7,8,9 cmd
if [ $num -eq 1 -o $num -eq 2 -o $num -eq 3 ] 写起来条件判断过长,这时用case。
case $num in
1|2|3)
cmd1
;;
4|5|6)
cmd2;
;;
7|8|9)
cmd3
;;
*)
cmd4
;;
esac
条件判断:case语句        case 适合条件是离散型的
case 变量引用 in                    case 后面的变量必须加$符号
PAT1)
分支1
;;
PAT2)
分支2
;;
*)
默认分支
;;
esac
case支持glob风格的通配符:
*: 任意长度任意字符
?: 任意单个字符
[]:指定范围内的任意单个字符
a|b: a或b
用case实现yes or no
[root@CENTOS7 ~]#vim test_case.sh
#!/bin/bash
#
#********************************************************************
#Author:                wangxiaochun
#QQ:                    29308620
#Date:                  2018-05-06
#FileName:             test_case.sh
#URL:                   http://www.magedu.com
#Description:          The test script
#Copyright (C):         2018 All rights reserved
#********************************************************************
read -p “do you agree:” ans
if [ -z “$ans” ] ; then
        echo “please input yes or no”
        exit
fi
case “$ans” in
[Yy] | [Yy][Ee][Ss])
        echo “your answer is yes”
        ;;
[Nn] | [Nn][Oo])
        echo “your answer is no”
        ;;
*)
        echo “your answer is false”
        ;;
esac

本文来自投稿,不代表Linux运维部落立场,如若转载,请注明出处:http://www.178linux.com/97606

(0)
上一篇 2018-05-06 15:20
下一篇 2018-05-06 15:34

相关推荐

  • Linux计算MD5和Sha1的命令

    Linux计算MD5和Sha1的命令

    Linux笔记 2018-06-07
  • 计算机的组成及功能(硬件及操作系统)

    主要从计算机的硬件和操作系统两方面介绍了计算机的组成及功能

    2018-05-11
  • 变量的理解

    有点绕多动动手就好了

    Linux笔记 2018-04-15
  • Linux系统网络管理

    本机索引: 一、基本网络配置 二、主机、网卡名称管理 三、网卡别名 四、Bonding技术 五、实现网络组 六、Linux网络管理常用命令   一、基本网络配置: 将Linux主机接入网络,需要配置网络相关设置 一般包括以下内容: 主机名 IP/netmask 路由:默认网关 DNS服务器: 主DNS服务器 次DNS服务器   网络配置文…

    2018-05-03
  • RHCE考试笔记

    (2)下午RHCE部分

    Linux笔记 2018-07-14
  • 参加马哥教育面授班

    很兴奋,今天是开班的第6天了,课程的具体安排为,1、3、5上课,2、4、6实操课。课堂上目前是王老师授课,讲的都是满满的干货,很详细。让我再次确信参加这次培训不会有错。 面授班与在网络学习,我觉得学习效果差别还是蛮大的。参加面授班能很好的约束我的行为,不会出现学着学着就打开游戏或看电影了,学习效率很高,哈哈。初次见到马哥教育的各个老师发现都很平易近人,学习上…

    Linux笔记 2018-07-21