Cent OS7之网络管理

TCP/IP 传输控制 网际协议

应用层:为用户提供所需的各种应用服务,如FTP、Telnet、DNS、SMTP等。

传输层:为应用层提供端到端的通信功能,同时提供流量控制,确保数据的完整和正确。TCP协议位于该层。

网际互联层:解决主机到主机之间的通信问题,包括网际协议(IP)、地址解析协议(ARP)、反向地址解析协议(RARP)、互联网控制报文协议(ICMP)。

网络接口层:完成链路控制等;
包(packet):网络上传输的数据片段,也称为IP数据报。

=====================================================================================================================================================
网络管理命令
ifconfig 
[root@luffy ~]# ifconfig
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.229.151  netmask 255.255.255.0  broadcast 192.168.229.255
        inet6 fe80::20c:29ff:fe41:19c1  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:41:19:c1  txqueuelen 1000  (Ethernet)
        RX packets 198051  bytes 289489676 (276.0 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 60404  bytes 4197413 (4.0 MiB)
        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 600  bytes 48344 (47.2 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 600  bytes 48344 (47.2 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
[root@luffy ~]# ifconfig ens33
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.229.151  netmask 255.255.255.0  broadcast 192.168.229.255
        inet6 fe80::20c:29ff:fe41:19c1  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:41:19:c1  txqueuelen 1000  (Ethernet)
        RX packets 198246  bytes 289503994 (276.0 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 60474  bytes 4205635 (4.0 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

[root@luffy ~]# 
[root@luffy ~]# 
-------------------------------------------------------------------------------------------
[root@luffy ~]# route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         gateway         0.0.0.0         UG    100    0        0 ens33
192.168.229.0   0.0.0.0         255.255.255.0   U     100    0        0 ens33
[root@luffy ~]#
添加一条路由:发往192.168.60.0网段的全部要经过192.168.19.1 
route add -net 192.168.60.0 netmask 255.255.255.0 gw 192.168.19.1


删除一条路由,删除时不需要网关
route del -net 192.168.60.0 netmask 255.255.255.0
-------------------------------------------------------------------------------------------
远程复制文件scp
scp -r root@192.168.61.147:/home/docker /home/

-P 指定远程端口
-q 把进度参数关掉
-r 递归地复制 
-V 冗余模式。打印拍错信息
-------------------------------------------------------------------------------------------
复制文件到其它系统rsync


数据镜像备份工具,用于在不同的主机之间的同步文件。
可保存整个目录树和文件系统,并可以增量同步,保存文件的属性权限等。
数据传输过程中是加密的 

Usage: rsync [OPTION]... SRC [SRC]... DEST
  or   rsync [OPTION]... SRC [SRC]... [USER@]HOST:DEST
  or   rsync [OPTION]... SRC [SRC]... [USER@]HOST::DEST
  or   rsync [OPTION]... SRC [SRC]... rsync://[USER@]HOST[:PORT]/DEST
  or   rsync [OPTION]... [USER@]HOST:SRC [DEST]
  or   rsync [OPTION]... [USER@]HOST::SRC [DEST]
  or   rsync [OPTION]... rsync://[USER@]HOST[:PORT]/SRC [DEST]
The ':' usages connect via remote shell, while '::' & 'rsync://' usages connect
to an rsync daemon, and require SRC or DEST to start with a module name.


-v, --verbose               increase verbosity
 -q, --quiet                 suppress non-error messages
     --no-motd               suppress daemon-mode MOTD (see manpage caveat)
 -c, --checksum              skip based on checksum, not mod-time & size
 -a, --archive               archive mode; equals -rlptgoD (no -H,-A,-X)
     --no-OPTION             turn off an implied OPTION (e.g. --no-D)
 -r, --recursive             recurse into directories
 -R, --relative              use relative path names
     --no-implied-dirs       don't send implied dirs with --relative
 -b, --backup                make backups (see --suffix & --backup-dir)
     --backup-dir=DIR        make backups into hierarchy based in DIR
     --suffix=SUFFIX         set backup suffix (default ~ w/o --backup-dir)
 -u, --update                skip files that are newer on the receiver
     --inplace               update destination files in-place (SEE MAN PAGE)
     --append                append data onto shorter files
     --append-verify         like --append, but with old data in file checksum
 -d, --dirs                  transfer directories without recursing
 -l, --links                 copy symlinks as symlinks
 -L, --copy-links            transform symlink into referent file/dir
     --copy-unsafe-links     only "unsafe" symlinks are transformed
     --safe-links            ignore symlinks that point outside the source tree
 -k, --copy-dirlinks         transform symlink to a dir into referent dir
 -K, --keep-dirlinks         treat symlinked dir on receiver as dir
 -H, --hard-links            preserve hard links
 -p, --perms                 preserve permissions
 -E, --executability         preserve the file's executability
     --chmod=CHMOD           affect file and/or directory permissions
 -A, --acls                  preserve ACLs (implies --perms)
 -X, --xattrs                preserve extended attributes
 -o, --owner                 preserve owner (super-user only)
 -g, --group                 preserve group
     --devices               preserve device files (super-user only)
     --copy-devices          copy device contents as regular file
     --specials              preserve special files
 -D                          same as --devices --specials
 -t, --times                 preserve modification times
 -O, --omit-dir-times        omit directories from --times
     --super                 receiver attempts super-user activities
     --fake-super            store/recover privileged attrs using xattrs
 -S, --sparse                handle sparse files efficiently
 -n, --dry-run               perform a trial run with no changes made
 -W, --whole-file            copy files whole (without delta-xfer algorithm)
 -x, --one-file-system       don't cross filesystem boundaries
 -B, --block-size=SIZE       force a fixed checksum block-size


 传输本地文件到远程主机
 
 传输目录到远程主机
 
 拉去远程文件到本地
 
 拉去远程目录到本地
 -------------------------------------------------------------------------------------------
显示网络连接、路由表或接口状态 netstat
[root@luffy ~]# netstat -h
usage: netstat [-vWeenNcCF] [<Af>] -r         netstat {-V|--version|-h|--help}
       netstat [-vWnNcaeol] [<Socket> ...]
       netstat { [-vWeenNac] -I[<Iface>] | [-veenNac] -i | [-cnNe] -M | -s [-6tuw] } [delay]


        -r, --route              display routing table
        -I, --interfaces=<Iface> display interface table for <Iface>
        -i, --interfaces         display interface table
        -g, --groups             display multicast group memberships
        -s, --statistics         display networking statistics (like SNMP)
        -M, --masquerade         display masqueraded connections


        -v, --verbose            be verbose
        -W, --wide               don't truncate IP addresses
        -n, --numeric            don't resolve names
        --numeric-hosts          don't resolve host names
        --numeric-ports          don't resolve port names
        --numeric-users          don't resolve user names
        -N, --symbolic           resolve hardware names
        -e, --extend             display other/more information
        -p, --programs           display PID/Program name for sockets
        -o, --timers             display timers
        -c, --continuous         continuous listing


        -l, --listening          display listening server sockets
        -a, --all                display all sockets (default: connected)
        -F, --fib                display Forwarding Information Base (default)
        -C, --cache              display routing cache instead of FIB
        -Z, --context            display SELinux security context for sockets


#显示所有端口,包含UDP和TCP
[root@luffy ~]# netstat -a|head -4
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 0.0.0.0:ssh             0.0.0.0:*               LISTEN     
tcp        0      0 localhost:smtp          0.0.0.0:*               LISTEN     
[root@luffy ~]#

#显示所有TCP端口
[root@luffy ~]# netstat -at
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 0.0.0.0:ssh             0.0.0.0:*               LISTEN     
tcp        0      0 localhost:smtp          0.0.0.0:*               LISTEN     
tcp        0     52 luffy:ssh               192.168.229.2:62937     ESTABLISHED
tcp6       0      0 [::]:ssh                [::]:*                  LISTEN     
tcp6       0      0 localhost:smtp          [::]:*                  LISTEN     
[root@luffy ~]# 

#显示所有UDP端口
[root@luffy ~]# netstat -au
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
udp        0      0 localhost:323           0.0.0.0:*                          
udp6       0      0 localhost:323           [::]:*                             
[root@luffy ~]#

#显示所有处于监控状态的端口并以数字方式显示而非服务名
[root@luffy ~]# netstat -ln
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN     
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN     
tcp6       0      0 :::22                   :::*                    LISTEN     
tcp6       0      0 ::1:25                  :::*                    LISTEN     
udp        0      0 127.0.0.1:323           0.0.0.0:*                          
udp6       0      0 ::1:323                 :::*                               
Active UNIX domain sockets (only servers)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  2      [ ACC ]     STREAM     LISTENING     19631    private/trace
unix  2      [ ACC ]     STREAM     LISTENING     19634    private/verify

#显示所有的TCP端口并显示对应的进程名称或进程号
[root@luffy ~]# netstat -plnt
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      969/sshd            
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1787/master         
tcp6       0      0 :::22                   :::*                    LISTEN      969/sshd            
tcp6       0      0 ::1:25                  :::*                    LISTEN      1787/master         
[root@luffy ~]# 


#显示核心路由信息
[root@luffy ~]# netstat -r
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
default         gateway         0.0.0.0         UG        0 0          0 ens33
192.168.229.0   0.0.0.0         255.255.255.0   U         0 0          0 ens33
[root@luffy ~]# 

#显示网络接口列表
[root@luffy ~]# netstat -i
Kernel Interface table
Iface      MTU    RX-OK RX-ERR RX-DRP RX-OVR    TX-OK TX-ERR TX-DRP TX-OVR Flg
ens33     1500   199681      0      0 0         61037      0      0      0 BMRU
lo       65536      600      0      0 0           600      0      0      0 LRU
[root@luffy ~]# 

#统计各个TCP连接的各个状态对应的数量
[root@luffy ~]# netstat -plnta|sed '1,2d'|awk '{print $6}'|sort | uniq -c
      1 ESTABLISHED
      4 LISTEN
[root@luffy ~]# 

-----------------------------------------------------------------------------------------------
探测至目的地址的路由信息traceroute
跟踪数据包到达网络主机所经过的路由,原理是试图以最小的TTL发出探测包来跟踪数据包到达目标主机所经过的网管,然后监听一个来自网关ICMP的应答。
[root@luffy ~]# traceroute -h
Bad option `-h' (argc 1)
[root@luffy ~]# traceroute 
Usage:
  traceroute [ -46dFITnreAUDV ] [ -f first_ttl ] [ -g gate,... ] [ -i device ] [ -m max_ttl ] [ -N squeries ] [ -p port ] [ -t tos ] [ -l flow_label ] [ -w waittime ] [ -q nqueries ] [ -s src_addr ] [ -z sendwait ] [ --fwmark=num ] host [ packetlen ]
Options:
  -4                          Use IPv4
  -6                          Use IPv6
  -d  --debug                 Enable socket level debugging
  -F  --dont-fragment         Do not fragment packets
  -f first_ttl  --first=first_ttl
                              Start from the first_ttl hop (instead from 1)
  -g gate,...  --gateway=gate,...
                              Route packets through the specified gateway
                              (maximum 8 for IPv4 and 127 for IPv6)
  -I  --icmp                  Use ICMP ECHO for tracerouting
  -T  --tcp                   Use TCP SYN for tracerouting (default port is 80)
  -i device  --interface=device
                              Specify a network interface to operate with
  -m max_ttl  --max-hops=max_ttl
                              Set the max number of hops (max TTL to be
                              reached). Default is 30
  -N squeries  --sim-queries=squeries
                              Set the number of probes to be tried
                              simultaneously (default is 16)
  -n                          Do not resolve IP addresses to their domain names
  -p port  --port=port        Set the destination port to use. It is either
                              initial udp port value for "default" method
                              (incremented by each probe, default is 33434), or
                              initial seq for "icmp" (incremented as well,
                              default from 1), or some constant destination
                              port for other methods (with default of 80 for
                              "tcp", 53 for "udp", etc.)
  -t tos  --tos=tos           Set the TOS (IPv4 type of service) or TC (IPv6
                              traffic class) value for outgoing packets
[root@luffy ~]# traceroute -n www.baidu.com
traceroute to www.baidu.com (119.75.213.61), 30 hops max, 60 byte packets
 1  192.168.229.1  0.116 ms  0.156 ms  0.150 ms
 2  * * *
 3  * * *
 4  * * *
 5  * * *
 6  * * *
 7  * * *
 8  * * *
 9  * * *
10  * * *
11  * * *
12  * * *
13  * * *
14  * * *
15  * * *
16  * * *
17  * * *
18  * * *
19  * * *
20  * * *
21  * * *
22  * * *
23  * * *
24  * * *
25  * * *
26  * * *
27  * * *
28  * * *
29  * * *
30  * * *

使用默认设置时,本地机给每个路由器发送3个数据包,最多经过30个路由器。如果经过30个路由器,还未到达目标机,traceroute将终止。
当到达路由器时,路由器就相应一个ICMPTimeExceed消息,于是traceroute就显示出当前跳步数,路由器的IP地址或名字,3个包分别对应的周转时间。
如果本地机在指定时间未收到响应包,那么数据包的周转时间就显示出一个*.

---------------------------------------------------------------------------------
测试、登录或控制远程主机 telnet
是基于TELNET协议的远程登录客户端程序
telnet可以确定远程服务端口的状态,以便确认服务是否正常。
[root@luffy ~]# telnet 192.168.61.147 1025
Trying 192.168.61.147...
Connected to 192.168.61.147.
Escape character is '^]'.
[root@luffy ~]# telnet www.baidu.com 80
Trying 119.75.213.61...
Connected to www.baidu.com.
Escape character is '^]'.

-----------------------------------------------------------------------------------
下载网络文件wget
[root@luffy ~]# wget -h
GNU Wget 1.14,非交互式的网络文件下载工具。
用法: wget [选项]... [URL]...

长选项所必须的参数在使用短选项时也是必须的。

启动:
  -V,  --version           显示 Wget 的版本信息并退出。
  -h,  --help              打印此帮助。
  -b,  --background        启动后转入后台。
  -e,  --execute=COMMAND   运行一个“.wgetrc”风格的命令。


日志和输入文件:
  -o,  --output-file=FILE    将日志信息写入 FILE。
  -a,  --append-output=FILE  将信息添加至 FILE。
  -d,  --debug               打印大量调试信息。
  -q,  --quiet               安静模式 (无信息输出)。
  -v,  --verbose             详尽的输出 (此为默认值)。
  -nv, --no-verbose          关闭详尽输出,但不进入安静模式。
       --report-speed=TYPE   Output bandwidth as TYPE.  TYPE can be bits.
  -i,  --input-file=FILE     下载本地或外部 FILE 中的 URLs。
  -F,  --force-html          把输入文件当成 HTML 文件。
  -B,  --base=URL            解析与 URL 相关的
                             HTML 输入文件 (由 -i -F 选项指定)。
       --config=FILE         Specify config file to use.

下载:
  -t,  --tries=NUMBER            设置重试次数为 NUMBER (0 代表无限制)。
       --retry-connrefused       即使拒绝连接也是重试。
  -O,  --output-document=FILE    将文档写入 FILE。
  -nc, --no-clobber              skip downloads that would download to
                                 existing files (overwriting them).
  -c,  --continue                断点续传下载文件。
       --progress=TYPE           选择进度条类型。
  -N,  --timestamping            只获取比本地文件新的文件。
  --no-use-server-timestamps     不用服务器上的时间戳来设置本地文件。
  -S,  --server-response         打印服务器响应。
       --spider                  不下载任何文件。
  -T,  --timeout=SECONDS         将所有超时设为 SECONDS 秒。
       --dns-timeout=SECS        设置 DNS 查寻超时为 SECS 秒。
       --connect-timeout=SECS    设置连接超时为 SECS 秒。
       --read-timeout=SECS       设置读取超时为 SECS 秒。
  -w,  --wait=SECONDS            等待间隔为 SECONDS 秒。
       --waitretry=SECONDS       在获取文件的重试期间等待 1..SECONDS 秒。
       --random-wait             获取多个文件时,每次随机等待间隔
                                 0.5*WAIT...1.5*WAIT 秒。
       --no-proxy                禁止使用代理。
  -Q,  --quota=NUMBER            设置获取配额为 NUMBER 字节。
       --bind-address=ADDRESS    绑定至本地主机上的 ADDRESS (主机名或是 IP)。
       --limit-rate=RATE         限制下载速率为 RATE。
       --no-dns-cache            关闭 DNS 查寻缓存。
       --restrict-file-names=OS  限定文件名中的字符为 OS 允许的字符。
       --ignore-case             匹配文件/目录时忽略大小写。
  -4,  --inet4-only              仅连接至 IPv4 地址。
  -6,  --inet6-only              仅连接至 IPv6 地址。
       --prefer-family=FAMILY    首先连接至指定协议的地址
                                 FAMILY 为 IPv6,IPv4 或是 none。
       --user=USER               将 ftp 和 http 的用户名均设置为 USER。
       --password=PASS           将 ftp 和 http 的密码均设置为 PASS。
       --ask-password            提示输入密码。
       --no-iri                  关闭 IRI 支持。
       --local-encoding=ENC      IRI (国际化资源标识符) 使用 ENC 作为本地编码。
       --remote-encoding=ENC     使用 ENC 作为默认远程编码。
       --unlink                  remove file before clobber.


目录:
  -nd, --no-directories           不创建目录。
  -x,  --force-directories        强制创建目录。
  -nH, --no-host-directories      不要创建主目录。
       --protocol-directories     在目录中使用协议名称。
  -P,  --directory-prefix=PREFIX  以 PREFIX/... 保存文件
       --cut-dirs=NUMBER          忽略远程目录中 NUMBER 个目录层。


====================================================================================================================================================
LINUX网络配置
/etc/hostname: 修改主机名
/etc/sysconfig/network-scripts/ifcfg-enoN:设置网卡参数的文件,如ip、子网掩码、广播地址、网关等;
/etc/resolve.conf : 此文件设置了DNS相关信息,用于将域名解析成ip。
/etc/hosts: 计算机的ip对应的主机名称或域名对应的IP地址,通过/etc/nsswitch.conf中的选项可设置是DNS解析优先还是本地设置优先。
/etc/nsswitch.conf(名字服务切换配置):通过哪些途径,以及按照什么顺序通过这些途径来查找特定类型的信息。


[root@luffy network-scripts]# cat ifcfg-ens33
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=static
DEFROUTE=yes
IPV4_FAILURE_FATAL=yes
IPV6INIT=no
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=ens33
UUID=44b5449f-e828-437e-ac6e-49cd3abed0e8
DEVICE=ens33
ONBOOT=yes
IPADDR=192.168.229.151
NETMASK=255.255.255.0
GATEWAY=192.168.229.1
DNS1=8.8.8.8
[root@luffy network-scripts]# 

需要重启网络服务才能生效
service network restart

主机名
[root@luffy ~]# hostname luffy
luffy
[root@luffy ~]# 

设置默认网关
(1)方式1:
route add default gw 192.168.61.254
(2)方式2:
在/etc/sysconfig/network-scripts/ifcfg-enoN文件中添加:
GATEWAY=192.168.61.254


需要重启服务
service network restart


设置DNS服务器
[root@luffy ~]# cat /etc/resolv.conf 
# Generated by NetworkManager
nameserver 8.8.8.8
[root@luffy ~]# 


=====================================================================================================================================================
LINUX防火墙
防火墙工作原理
通过netfilter框架实现,不依赖于具体协议,而是为每种网络协议定义了一套钩子函数。钩子函数在数据包经过协议栈的几个关键点时被调用,在这几个点中,协议栈将数据包和钩子函数作为参数,传递给netfilter框架。


iptalbes
#关闭禁用firewalld
[root@luffy ~]# firewall-cmd    --state
running
[root@luffy ~]# systemctl  stop   firewalld
[root@luffy ~]# systemctl  disabled   firewalld
Unknown operation 'disabled'.
[root@luffy ~]# systemctl  disable   firewalld
Removed symlink /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
[root@luffy ~]# firewall-cmd    --state
not running
[root@luffy ~]# 


#启动并启用iptables
[root@luffy ~]# systemctl  status  iptables
Unit iptables.service could not be found.
[root@luffy ~]# systemctl  status  iptables.service
Unit iptables.service could not be found.


[root@luffy ~]# yum install iptables-services 
已加载插件:fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.163.com
 * extras: mirrors.163.com
 * updates: mirrors.163.com
正在解决依赖关系
--> 正在检查事务
---> 软件包 iptables-services.x86_64.0.1.4.21-18.2.el7_4 将被 安装
--> 解决依赖关系完成



[root@luffy ~]# systemctl  status  iptables
● iptables.service - IPv4 firewall with iptables
   Loaded: loaded (/usr/lib/systemd/system/iptables.service; disabled; vendor preset: disabled)
   Active: inactive (dead)
[root@luffy ~]#


[root@luffy ~]# systemctl start iptables
[root@luffy ~]# systemctl enable iptables
Created symlink from /etc/systemd/system/basic.target.wants/iptables.service to /usr/lib/systemd/system/iptables.service.
[root@luffy ~]# 


● iptables.service - IPv4 firewall with iptables
   Loaded: loaded (/usr/lib/systemd/system/iptables.service; enabled; vendor preset: disabled)
   Active: active (exited) since 日 2018-02-11 20:08:56 CST; 36s ago
 Main PID: 11291 (code=exited, status=0/SUCCESS)


2月 11 20:08:56 luffy systemd[1]: Starting IPv4 firewall with iptables...
2月 11 20:08:56 luffy iptables.init[11291]: iptables: Applying firewall rules: [  确定  ]
2月 11 20:08:56 luffy systemd[1]: Started IPv4 firewall with iptables.
[root@luffy ~]#


#各个链中的规则匹配顺序
[root@luffy ~]# iptables -nvL
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         
   99  6584 ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            state RELATED,ESTABLISHED
    0     0 ACCEPT     icmp --  *      *       0.0.0.0/0            0.0.0.0/0           
    0     0 ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0           
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            state NEW tcp dpt:22
   16  1399 REJECT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            reject-with icmp-host-prohibited


Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 REJECT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            reject-with icmp-host-prohibited


Chain OUTPUT (policy ACCEPT 56 packets, 5792 bytes)
 pkts bytes target     prot opt in     out     source               destination         
[root@luffy ~]# 


iptables配置实例
[root@luffy ~]# iptables -h
iptables v1.4.21


Usage: iptables -[ACD] chain rule-specification [options]
       iptables -I chain [rulenum] rule-specification [options]
       iptables -R chain rulenum rule-specification [options]
       iptables -D chain rulenum [options]
       iptables -[LS] [chain [rulenum]] [options]
       iptables -[FZ] [chain] [options]
       iptables -[NX] chain
       iptables -E old-chain-name new-chain-name
       iptables -P chain target [options]
       iptables -h (print this help information)


Commands:
Either long or short options are allowed.
  --append  -A chain            Append to chain
  --check   -C chain            Check for the existence of a rule
  --delete  -D chain            Delete matching rule from chain
  --delete  -D chain rulenum
                                Delete rule rulenum (1 = first) from chain
  --insert  -I chain [rulenum]
                                Insert in chain as rulenum (default 1=first)
  --replace -R chain rulenum
                                Replace rule rulenum (1 = first) in chain
  --list    -L [chain [rulenum]]
                                List the rules in a chain or all chains
  --list-rules -S [chain [rulenum]]
                                Print the rules in a chain or all chains
  --flush   -F [chain]          Delete all rules in  chain or all chains
  --zero    -Z [chain [rulenum]]
                                Zero counters in chain or all chains
  --new     -N chain            Create a new user-defined chain
  --delete-chain
            -X [chain]          Delete a user-defined chain
  --policy  -P chain target
                                Change policy on chain to target
  --rename-chain
            -E old-chain new-chain
                                Change chain name, (moving any references)


#清除所有规则
[root@luffy ~]# iptables -F
#清除nat表中所有规则
[root@luffy ~]# iptables -t nat -F
#允许来自192.168.229.0/24连接sshd服务
[root@luffy ~]# iptables -A INPUT -p tcp -s 192.168.229.0/24 --dport 22 -j ACCEPT
#其它网段不能访问sshd服务
[root@luffy ~]# iptables -A INPUT -p tcp --dport 22 -j DROP
[root@luffy ~]# 
-F 表示清除已存在的所有规则
-A 表示添加一条规则
-p 指定协议为TCP
-s 指定源地址段 如果该参数忽略或为0.0.0.0/0,则源地址表示任何地址
-dport 指定目的端口,


iptables可以为每个链指定默认规则,如果包不符合现存的所有规则,则按默认规则处理。


======================================================================================================================================
高级网络管理工具


Usage: ip [ OPTIONS ] OBJECT { COMMAND | help }
       ip [ -force ] -batch filename
where  OBJECT := { link | address | addrlabel | route | rule | neigh | ntable |
                   tunnel | tuntap | maddress | mroute | mrule | monitor | xfrm |
                   netns | l2tp | macsec | tcp_metrics | token }
       OPTIONS := { -V[ersion] | -s[tatistics] | -d[etails] | -r[esolve] |
                    -h[uman-readable] | -iec |
                    -f[amily] { inet | inet6 | ipx | dnet | bridge | link } |
                    -4 | -6 | -I | -D | -B | -0 |
                    -l[oops] { maximum-addr-flush-attempts } |
                    -o[neline] | -t[imestamp] | -ts[hort] | -b[atch] [filename] |
                    -rc[vbuf] [size] | -n[etns] name | -a[ll] }
[root@luffy ~]# 
[root@luffy ~]# ip addr list
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:41:19:c1 brd ff:ff:ff:ff:ff:ff
    inet 192.168.229.151/24 brd 192.168.229.255 scope global ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fe41:19c1/64 scope link 
       valid_lft forever preferred_lft forever
[root@luffy ~]# 
[root@luffy ~]# 
#添加网络地址
[root@luffy ~]# ip addr add 192.168.128.140/24 dev ens33
[root@luffy ~]# ip addr list
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:41:19:c1 brd ff:ff:ff:ff:ff:ff
    inet 192.168.229.151/24 brd 192.168.229.255 scope global ens33
       valid_lft forever preferred_lft forever
    inet 192.168.128.140/24 scope global ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fe41:19c1/64 scope link 
       valid_lft forever preferred_lft forever
[root@luffy ~]# 
#删除网络地址
[root@luffy ~]# ip addr del 192.168.128.140/24 dev ens33
[root@luffy ~]# 
[root@luffy ~]# ip addr list
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:41:19:c1 brd ff:ff:ff:ff:ff:ff
    inet 192.168.229.151/24 brd 192.168.229.255 scope global ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::20c:29ff:fe41:19c1/64 scope link 
       valid_lft forever preferred_lft forever
[root@luffy ~]# 


显示路由信息
[root@luffy ~]# ip route list
default via 192.168.229.1 dev ens33 proto static metric 100 
192.168.229.0/24 dev ens33 proto kernel scope link src 192.168.229.151 metric 100 
[root@luffy ~]#
[root@luffy ~]# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.229.1   0.0.0.0         UG    100    0        0 ens33
192.168.229.0   0.0.0.0         255.255.255.0   U     100    0        0 ens33
[root@luffy ~]# 
添加路由 
[root@luffy ~]# ip route add 192.168.30.1 dev ens33
[root@luffy ~]# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.229.1   0.0.0.0         UG    100    0        0 ens33
192.168.30.1    0.0.0.0         255.255.255.255 UH    0      0        0 ens33
192.168.229.0   0.0.0.0         255.255.255.0   U     100    0        0 ens33
[root@luffy ~]# 


网络数据采集与分析工具tcpdump
支持对网络层、协议、主机、网络或端口的过滤,并提供 and 、or、 not等逻辑语句过滤不必要的信息。
Usage: tcpdump [-aAbdDefhHIJKlLnNOpqStuUvxX#] [ -B size ] [ -c count ]
                [ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]
                [ -i interface ] [ -j tstamptype ] [ -M secret ] [ --number ]
                [ -Q|-P in|out|inout ]
                [ -r file ] [ -s snaplen ] [ --time-stamp-precision precision ]
                [ --immediate-mode ] [ -T type ] [ --version ] [ -V file ]
                [ -w file ] [ -W filecount ] [ -y datalinktype ] [ -z postrotate-command ]
                [ -Z user ] [ expression ]
[root@luffy ~]#  


[root@luffy ~]# tcpdump -i any
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on any, link-type LINUX_SLL (Linux cooked), capture size 262144 bytes
15:14:27.192181 IP luffy.ssh > 192.168.229.2.50666: Flags [P.], seq 654158689:654158885, ack 1888840426, win 255, length 196
15:14:27.192810 IP 192.168.229.2.50666 > luffy.ssh: Flags [.], ack 196, win 2050, length 0
15:14:27.193938 IP luffy.38086 > google-public-dns-a.google.com.domain: 54045+ PTR? 2.229.168.192.in-addr.arpa. (44)
15:14:27.246395 IP google-public-dns-a.google.com.domain > luffy.38086: 54045 NXDomain 0/0/0 (44)
15:14:27.247787 IP luffy.46425 > google-public-dns-a.google.com.domain: 57670+ PTR? 151.229.168.192.in-addr.arpa. (46)
15:14:27.252553 IP google-public-dns-a.google.com.domain > luffy.46425: 57670 NXDomain* 0/1/0 (101)
15:14:27.252820 IP luffy.55529 > google-public-dns-a.google.com.domain: 53708+ PTR? 8.8.8.8.in-addr.arpa. (38)
15:14:27.252973 IP luffy.ssh > 192.168.229.2.50666: Flags [P.], seq 196:456, ack 1, win 255, length 260
15:14:27.303760 IP 192.168.229.2.50666 > luffy.ssh: Flags [.], ack 456, win 2049, length 0


[root@luffy ~]# 
[root@luffy ~]# tcpdump -i any tcp  and dst host 192.168.229.151
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on any, link-type LINUX_SLL (Linux cooked), capture size 262144 bytes
15:20:48.696121 IP 192.168.229.2.50666 > luffy.ssh: Flags [.], ack 654542073, win 2049, length 0
15:20:48.756476 IP 192.168.229.2.50666 > luffy.ssh: Flags [.], ack 149, win 2049, length 0
15:20:48.806602 IP 192.168.229.2.50666 > luffy.ssh: Flags [.], ack 281, win 2048, length 0
15:20:48.857186 IP 192.168.229.2.50666 > luffy.ssh: Flags [.], ack 413, win 2048, length 0
15:20:48.908565 IP 192.168.229.2.50666 > luffy.ssh: Flags [.], ack 545, win 2047, length 0
15:20:48.958916 IP 192.168.229.2.50666 > luffy.ssh: Flags [.], ack 677, win 2053, length 0
15:20:49.008933 IP 192.168.229.2.50666 > luffy.ssh: Flags [.], ack 809, win 2052, length 0
15:20:49.059380 IP 192.168.229.2.50666 > luffy.ssh: Flags [.], ack 941, win 2052, length 0
时间 源IP端口和目的IP和端口 TCP中的标志信息


[root@luffy ~]# tcpdump -i any tcp  and dst host 192.168.229.151 and dst port 80 -s100 -XX -n
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on any, link-type LINUX_SLL (Linux cooked), capture size 100 bytes


-i any 表示截获本机所有网络接口的数据包。
tcp 表示TCP协议
dst host 表示数据包地址为192.168.229.151 
dst port 表示目的地址为 80 
-XX 表示同时会以十六进制和ASCII码形式打印出每个包的数据
-s100 表示设置tcpdump的数据包抓取长度为100个字节,如果不设置默认68字节
-n 表示不对地址如主机地址或端口号进行数字表示到名字表示的转换。

==================================================================================================================================================

动态主机配置协议(DHCP)
基于C/S模式,主要用于大型网络。
提供一种动态指定IP地址和相关网络配置参数的机制


工作原理:每个DHCP客户端通过广播连接到区域内的DHCP服务器,该服务器会相应请求返回包括IP地址、网关和其他网络配信息。


配置DHCP服务器
[root@luffy ~]# yum install dhcp
已加载插件:fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.163.com
 * extras: mirrors.163.com
 * updates: mirrors.163.com
正在解决依赖关系
--> 正在检查事务
---> 软件包 dhcp.x86_64.12.4.2.5-58.el7.centos.1 将被 安装
--> 解决依赖关系完成


依赖关系解决


[root@luffy ~]# rpm -qa|grep dhcp
dhcp-4.2.5-58.el7.centos.1.x86_64
dhcp-libs-4.2.5-58.el7.centos.1.x86_64
dhcp-common-4.2.5-58.el7.centos.1.x86_64
[root@luffy ~]#  /etc/dhcp/dhcpd.conf DHCP主配置文件
[root@luffy system]#/usr/lib/systemd/system/dhcpd.service DHCP服务单元


dhcpd.conf配置实例
#指定接口DHCP请求的网卡的子网地址,注意不是本机的IP地址。netmask为子网掩码
subnet 192.168.229.0 netmask 255.255.255.0{
#指定默认网关
option routers 192.168.229.1;
#指定默认子网掩码
option subnet -mask 255.255.255.0;
#指定最大租用周期
max-lease-time 172800;
#此DHCP服务器分配的IP地址范围
range 192.168.229.230 192.168.229.240;
}

启动dhcp服务
systemctl start dhcpd.service 

配置DHCP客户端

[root@luffy system]# cat /etc/sysconfig/network-scripts/ifcfg-ens33 
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=static
DEFROUTE=yes
IPV4_FAILURE_FATAL=yes
IPV6INIT=no
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=ens33
UUID=44b5449f-e828-437e-ac6e-49cd3abed0e8
DEVICE=ens33
ONBOOT=yes
IPADDR=192.168.229.151
NETMASK=255.255.255.0
GATEWAY=192.168.229.1
DNS1=8.8.8.8
[root@luffy system]# 
如果需要使用DHCP服务,BOOTPROTO=dhcp ,表示当前主机网络ip自动获取

======================================================================================================================================================
域名服务DNS
负责将域名解析为ip地址
dns是一个分布式数据库系统
查询方式有两种:递归和迭代


[root@luffy ~]# yum install -y bind bind-utils
已加载插件:fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.163.com
 * extras: mirrors.163.com
 * updates: mirrors.163.com
正在解决依赖关系
--> 正在检查事务
---> 软件包 bind.x86_64.32.9.9.4-51.el7_4.2 将被 安装


#DNS主配置文件
[root@luffy ~]# cat /etc/named.conf
//
// named.conf
//
// Provided by Red Hat bind package to configure the ISC BIND named(8) DNS
// server as a caching only nameserver (as a localhost DNS resolver only).
//
// See /usr/share/doc/bind*/sample/ for example named configuration files.
//
// See the BIND Administrator's Reference Manual (ARM) for details about the
// configuration located in /usr/share/doc/bind-{version}/Bv9ARM.html


options {
        listen-on port 53 { 127.0.0.1; };
        listen-on-v6 port 53 { ::1; };
        directory       "/var/named";
        dump-file       "/var/named/data/cache_dump.db";
        statistics-file "/var/named/data/named_stats.txt";
        memstatistics-file "/var/named/data/named_mem_stats.txt";
        allow-query     { localhost; };


        /* 
         - If you are building an AUTHORITATIVE DNS server, do NOT enable recursion.
         - If you are building a RECURSIVE (caching) DNS server, you need to enable 
           recursion. 
         - If your recursive DNS server has a public IP address, you MUST enable access 
           control to limit queries to your legitimate users. Failing to do so will
           cause your server to become part of large scale DNS amplification 
           attacks. Implementing BCP38 within your network would greatly
           reduce such attack surface 
        */
        recursion yes;


        dnssec-enable yes;
        dnssec-validation yes;


        /* Path to ISC DLV key */
        bindkeys-file "/etc/named.iscdlv.key";


        managed-keys-directory "/var/named/dynamic";


        pid-file "/run/named/named.pid";
        session-keyfile "/run/named/session.key";
};


logging {
        channel default_debug {
                file "data/named.run";
                severity dynamic;
        };
};


zone "." IN {
        type hint;
        file "named.ca";
};


include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";

[root@luffy ~]# 
options:全局服务器的配置选项
listen-on port:
directory:
dump-file:
statistics-file:
allow-query:
zone:

[root@luffy system]#/usr/lib/systemd/system/named.service DNS服务单元

启动dns服务
systemctl start named.service 

DNS服务器地址配置
/etc/resolv.conf 

[root@luffy ~]# nslookup baidu.com
Server:         8.8.8.8
Address:        8.8.8.8#53


Non-authoritative answer:
Name:   baidu.com
Address: 220.181.57.216
Name:   baidu.com
Address: 123.125.114.144
Name:   baidu.com

Address: 111.13.101.208

路由管理
route add|del [-net|-host] ipaddress1 netmask netmask gw ipaddress2|dev 

route还可以添加默认路由,通常称为网关,但更多的是添加静态路由

route add default gw 172.16.45.1
route del default gw 172.16.35.1

route add -net 192.168.19.0/24 gw 172.16.45.100
route add -net 192.168.19.0 netmask 255.255.255.0 gw 172.16.45.100

添加到主机的路由
route add -host 192.168.100.80 gw 172.16.45.100
删除到主机的路由
route del -host 192.168.100.80 

路由配置实例

[root@luffy ~]# cat /etc/sysctl.conf
net.ipv4.ip_forward = 1

让参数生效
[root@luffy etc]# sysctl -p
net.ipv4.ip_forward = 1
[root@luffy etc]#

让防火墙具体NAT功能
[root@luffy ~]# systemctl disable firewalld
[root@luffy ~]# systemctl stop firewalld
[root@luffy ~]# 
[root@luffy ~]# yum install -y iptables-services
已加载插件:fastestmirror
软件包 iptables-services-1.4.21-18.2.el7_4.x86_64 已安装并且是最新版本
无须任何处理
[root@luffy ~]# 
[root@luffy ~]# systemctl start iptables
[root@luffy ~]# systemctl enable iptables
[root@luffy ~]# 
[root@luffy ~]# ip rule list
0:      from all lookup local 
32766:  from all lookup main 
32767:  from all lookup default 
[root@luffy ~]# 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值