Linux network settings (ifconfig, route, traceroute, netstat, ss, nslookup, dig)

1. Check the network

1. Check the network interface address

The host's network interface card (network card) is usually called a network interface. In the Linux operating system, use the ifconfig command to view the address configuration information of the network interface (Interface Configuration).
Note: If there is no ifconfig command, you need to install the net-tools software package through yum before the ifconfig command is available.

第一种方法查看
[root@localhost ~]# ifconfig 
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.10.8  netmask 255.255.255.0  broadcast 192.168.10.255
        inet6 fe80::8c58:4d06:fde9:2d7d  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:fe:06:f3  txqueuelen 1000  (Ethernet)
        RX packets 684409  bytes 987345087 (941.6 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 175406  bytes 15317449 (14.6 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 135  bytes 12160 (11.8 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 135  bytes 12160 (11.8 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
第二种方法查看
[root@localhost ~]# 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:fe:06:f3 brd ff:ff:ff:ff:ff:ff
    inet 192.168.10.8/24 brd 192.168.10.255 scope global ens33
       valid_lft forever preferred_lft forever
    inet6 fe80::8c58:4d06:fde9:2d7d/64 scope link 
  • ens33: The name of the first Ethernet card. The "en" in "ens33" is the abbreviation of "EtherNet", which means that the network card type is Ethernet.
  • lo: "loopback" network interface, "lo" is the abbreviation of "loopback", it does not represent a real network interface, but a virtual network interface, the default IP address is "127.0.0.1". The loopback address is usually only used for network testing of this machine.
  • inet: Represents the IP address of the network interface.
  • netmask: indicates the subnet mask of the network interface.
  • broadcast: Represents the broadcast address of the network where the network interface is located.
  • ether: indicates the physical address (MAC address) of the network interface.
  • "TX" The number and flow of data packets sent through the network interface.
  • "RX" The number and flow of data packets received through the network interface.

2. View and change the host name

In the Linux operating system, a considerable part of the network services will identify the host by the host name. If the host name is not configured properly, it may cause the program function to malfunction. Use the hostname command to view the host name of the current host.

方法一
[root@localhost ~]# hostname	//查看原来的主机名
localhost.localdomain
[root@localhost ~]# hostname www	//设置新的主机名
[root@localhost ~]# hostname	//确认新的主机名
www
[root@localhost ~]# bash	//启用新的Shell 会话,查看变化
[root@www ~]#hostname 
www
方法二
[root@localhost ~]# vi /etc/hostname
www
通过修改/etc/hostname 来更改的主机名,如果要让其生效,需重启 Linux 系统。
方法三
[root@localhost ~]# hostnamectl set-hostname www     //设置新的主机名
[root@localhost ~]# bash	//启用新的Shell 会话,查看变化
[root@www ~]#hostname
www

3. View routing table entries

[root@localhost ~]# 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.10.0    0.0.0.0         255.255.255.0   U     100    0        0 ens33
[root@localhost ~]# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.10.2    0.0.0.0         UG    100    0        0 ens33
192.168.10.0    0.0.0.0         255.255.255.0   U     100    0        0 ens33
  • The Destination column corresponds to the address of the target network segment
  • The Gateway column corresponds to the address of the next hop router
  • The Iface column corresponds to the network interface that sends data
  • If used in combination with the "-n" option, the address in the routing record can be displayed as a number, which can skip the process of resolving the host name and speed up the execution when there are many routing table entries.

4. Check the network connection

netstat command

The netstat command can be used to view the current operating system's network connection status, routing table, interface statistics and other information. It is an effective tool for understanding the network status and troubleshooting network service failures.
Commonly used options of netstat command:

  • -a: Display all active network connection information in the host (including service ports in listening and non-monitoring states).
  • -n: Display related host address, port and other information in digital form.
  • -r: Display routing table information.
  • -l: Display the network connection and port information in the listening state.
  • -t: View information related to TCP (Transmission Control Protocol, Transmission Control Protocol).
  • -u: Display UDP (User Datagram Protocol, user datagram protocol) protocol related information.
  • -p: Display the process number and process name information associated with the network connection (this option requires root privileges).

Usually the "-anpt" combination option is used to display all the TCP connection information in the current system in digital form and the
corresponding process information at the same time .

[root@localhost ~]# netstat -anpt
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      1/systemd           
tcp        0      0 192.168.122.1:53        0.0.0.0:*               LISTEN      1338/dnsmasq        
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1024/sshd 
ss command

The ss command can also check the network connection. It is the abbreviation of Socket Statistics and is mainly used to obtain socket statistics. It can display output similar to the netstat command. But the advantage of ss is that it can display more and more detailed information about TCP and connection status, and it is faster and more efficient than netstat. To use the ss command, first make sure that the iproute package has been installed, which can be installed via yum.
Commonly used options of ss command

  • -h: -help Use this option to get more help.
  • -V: -version Display the version number of the software.
  • -t: -tcp displays the sockets of the TCP protocol.
  • -u: -udp Display UDP protocol sockets.
  • -n: -numeric does not resolve the name of the service, such as "22" port will not be displayed as "ssh".
  • -l: -listening only displays ports that are in the listening state.
  • -p: -processes Display the processes of the listening port.
  • -a: --all For the TCP protocol, it includes both the listening port and the established connection.
  • -r: --resolve Interpret IP as a domain name and port number as a protocol name.
[root@localhost ~]# ss -anpt
State       Recv-Q Send-Q Local Address:Port                Peer Address:Port              
LISTEN      0      128                *:111                            *:*                   users:(("systemd",pid=1,fd=43))
LISTEN      0      5      192.168.122.1:53                             *:* 
  • "Local Address: Port" represents the local listening IP and port
  • "Peer Address: Port" indicates the IP and port of the remote connection

2. Test the network connection

The premise for users to access network services is that the network connection is in a normal state. If the network connection is unstable or even unable to connect, the user cannot access the network service normally. Therefore, when there is a problem with the network connection, the command to test the network connection is required to determine the point of failure.

1. Test network connectivity

Use the ping command to continuously send test data packets to the target host and display the feedback results until the
test is aborted after pressing the Ctrl + C key combination, and the final statistical results are displayed.

[root@localhost ~]# ping www.baidu.com
PING www.wshifen.com (103.235.46.39) 56(84) bytes of data.
64 bytes from 103.235.46.39 (103.235.46.39): icmp_seq=1 ttl=128 time=210 ms
64 bytes from 103.235.46.39 (103.235.46.39): icmp_seq=2 ttl=128 time=210 ms
[root@localhost ~]# ping 192.168.10.1
PING 192.168.10.1 (192.168.10.1) 56(84) bytes of data.
64 bytes from 192.168.10.1: icmp_seq=1 ttl=64 time=0.182 ms
64 bytes from 192.168.10.1: icmp_seq=2 ttl=64 time=0.355 ms

When the ping test command is executed, if the feedback data packet sent back from the target host cannot be obtained, it indicates that there is a network connectivity failure between the local machine and the target host.

  • If you see the "Destination Host Unreachable" feedback message, it means that the destination host is unreachable. Maybe the destination address does not exist or the host has been shut down.
  • If you see the "Network is unreachable" feedback message, it means that there is no available routing record (such as the default gateway) and the network where the target host is located cannot be reached.
  • The feedback result of "Request timeout" indicates that the connection with the target host has timed out (data packet response is slow or lost). In addition, when there are factors that affect the stability of the communication process in the network (such as network card failure, viruses or network attacks, etc.) or when the target host has strict firewall restrictions, you may also receive a "Request timeout" feedback result.

2. Track the routing path of data packets

  • If there is no traceroute command on the server, you can install the traceroute software package through yum. The traceroute command can be used to test which network nodes have passed from the current host to the destination host, and display the connection status (response time) of each intermediate node. For nodes that cannot respond, the connection status will be displayed as "*".

  • The traceroute command can locate the fault point (interruption point) of the network connection more accurately than the ping command, so the execution speed will be slightly slower than the ping command. In the process of network testing and troubleshooting, the ping command is usually used to test the network connection with the destination host first. If the network connection is found to be faulty, the traceroute command is used to track and check which intermediate node has the fault.

方法一
[root@localhost ~]# traceroute www.baidu.com    
traceroute to www.baidu.com (104.193.88.123), 30 hops max, 60 byte packets
 1  gateway (192.168.10.2)  0.050 ms  0.026 ms  0.023 ms
 2  * * *
 3  * * *
方法二
[root@localhost ~]# mtr www.baidu.com     
                                  My traceroute  [v0.85]
localhost.localdomain (0.0.0.0)                                     Mon Nov  2 10:00:17 2020
Resolver: Received error response 2. (server failure)er of fields   quit
                                                    Packets               Pings
 Host                                             Loss%   Snt   Last   Avg  Best  Wrst StDev
 1. 192.168.10.2                                   0.0%    19    0.2   0.4   0.2   1.2   0.0
 2. 192.168.1.1                                    0.0%    19    1.7   1.4   1.1   1.9   0.0
 3. 192.168.0.1                                    0.0%    18    3.2   2.1   1.4   3.2   0.2
 4. 100.94.128.1                                   0.0%    18   56.8  16.4   2.9 103.3  26.7
 5. 58.217.231.37                                  0.0%    18    5.0   4.9   3.0   6.9   1.0

3. Test DNS domain name resolution

nslookup command
  • When the domain name resolution is abnormal, you will not be able to use the domain name to access services such as Web sites and email systems on the network. The nslookup command is a special tool for testing domain name resolution. When using it, you only need to specify the target domain name to be resolved as a parameter. If you are prompted that the nslookup command cannot be found during the execution, you can use yum to install the bind-utils package to solve it.
[root@localhost ~]# nslookup www.caidu.com
Server:		8.8.8.8          //所使用的DNS 服务器
Address:	8.8.8.8#53

Non-authoritative answer:      //DNS 解析的反馈结果
Name:	www.caidu.com
Address: 45.76.29.156

  • If the message "... no servers could be reached" appears, it means that the specified DNS server cannot be connected.
  • If the message "... can't find xxx.yyy.zzz: NXDOMAIN" appears, it means that the domain name to be queried does not exist.
dig command
[root@localhost ~]# dig baidu.com

; <<>> DiG 9.9.4-RedHat-9.9.4-50.el7 <<>> baidu.com // dig 的版本及输入参数
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 37833
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1
//以上显示服务器返回的信息,status 为 NOERROR 状态说明查询成功
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;baidu.com.			IN	A
//显示通过 A 记录要查询的域名
;; ANSWER SECTION:
baidu.com.		498	IN	A	220.181.38.148
baidu.com.		498	IN	A	39.156.69.79
//经DNS 返回后的查询结果
;; Query time: 41 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)
;; WHEN: 一 11月 02 10:14:31 CST 2020
;; MSG SIZE  rcvd: 70
//查询后的一些统计信息,比如用了 41 毫秒,查询 DNS 服务器的IP 地址,查询的时间等等

dig 在查询过程中,还可以指定特点的 DNS 服务器。
如果不指定 DNS 服务器,默认会使用/etc/resolve.conf 里面的地址作为 DNS 服务器。
[root@localhost ~]# dig @8.8.8.8 baidu.com

Three, use network configuration commands

1. Explanation of temporary configuration and permanent configuration

  • Temporary configuration: directly modify the network address currently in use through the command line, and the modification can take effect immediately. This method is simple and fast in operation and efficient in execution. It is generally used in the process of network debugging. However, since the changes made are not stored in static files, they will become invalid when the network service is restarted or the host is restarted.
  • Fixed configuration: Store various fixed network addresses through configuration files, which will take effect only after restarting the network service or restarting the host. This method is relatively complicated in operation, but it is equivalent to "permanent configuration" and is generally used when a fixed network address needs to be set for the server.

2. Modify the address and status of the network card

ifconfig network interface name IP address[ netmask subnet mask]
ifconfig network interface name IP address[/subnet mask length]

  • In the process of debugging the server network, sometimes it is necessary to temporarily use a new IP address on the same network card, but the original IP address cannot be overwritten and the service program is unavailable. At this time, a virtual network interface can be bound to the network card, and the IP address of the virtual interface and the original IP address of the network card can be used normally.
  • [root@localhost ~]# ifconfig ens33:0 192.168.10.55
  • You can add more virtual interfaces as needed, such as "ens33:1" "ens33:2" and so on.

2. Add or delete static route and default route records

  • Through the "route add" operation, you can add routing records, combined with the "-net" option to specify the address of the target network segment, combined with the "gw" option to specify the IP address of the next hop router
    [root@www ~]# route add -net target network Next hop address of segment gw
    [root@www ~]# route del -net Next hop address of target network segment gw
  • When adding or deleting default gateway records, the command format is similar to adding and deleting static routing records, but when specifying the target network segment, you only need to simply use "default" to indicate that it is no longer necessary to use the "-net" option to specify the network segment address .
    [root@www ~]# route del default gw gateway address//delete the default gateway record
    [root@www ~]# route add default gw gateway address//add a new default gateway record

Fourth, modify the network configuration file

1. Network interface configuration file

The configuration file of the network interface is located in the directory /etc/sysconfig/network-scripts/ by default, and the file name format is "ifcfg-XXX", where "XXX" is the name of the network interface.

[root@localhost ~]# ls /etc/sysconfig/network-scripts/ifcfg-*
/etc/sysconfig/network-scripts/ifcfg-ens33  
/etc/sysconfig/network-scripts/ifcfg-lo
/etc/sysconfig/network-scripts/ifcfg-ens36
[root@localhost network-scripts]# vim ifcfg-ens36
TYPE="Ethernet"
BOOTPROTO="static"
DEFROUTE="yes"
DEVICE="ens36"
ONBOOT="yes"
IPADDR="192.168.20.1"
NETMASK="255.255.255.0"
GATEWAY="192.168.20.254"
  • TYPE: Set the network card type, "Ethernet" means Ethernet.
  • BOOTPROTO: Set the configuration method of the network interface. When the value is "static", it means that the statically specified IP
    address is used; when it is "dhcp", it means that the address is dynamically obtained through DHCP.
  • DEVICE: Set the name of the network interface.
  • ONBOOT: Set whether the network interface is activated when the Linux operating system starts.
  • IPADDR: Set the IP address of the network interface.
  • ETMASK: Set the subnet mask of the network interface.
  • GATEWAY: Set the default gateway address of the network interface.

2. Enable and disable network interface configuration

1) Enable the network interface
[root@localhost ~]# systemctl restart network //Restart the network service
//It will first shut down all network interfaces, and then re-enable all network interfaces according to the configuration file.
//In the real environment, it is not recommended to use
[root@localhost ~]# ifup ens33 or ifconfig ens33 up
2) Close the network interface
[root@localhost ~]# ifup ens33 or ifconfig ens33 down

3. Domain name resolution configuration file

1) Specify the address of the server that provides DNS resolution
for this machine. The /etc/resolv.conf file records the address information of the DNS server used by this machine by default. Modifications to this file will take effect immediately. Up to 3 different DNS server addresses can be specified in the Linux operating system (the third and subsequent ones will be ignored), and the first DNS server will be used first.

 [root@localhost ~]# vim /etc/resolv.conf
# Generated by NetworkManager
nameserver 8.8.8.8
nameserver 114.114.114.114
  • However, in the CentOS 7 environment, if you configure it in the above manner, it will be overwritten or cleared by the system after a period of time. At this time, you need to modify the /etc/NetworkManager/NetworkManager.conf file and add the "dns=none" configuration item in the main section . You need to restart the NetworkManager service afterwards. Make sure there is configuration information in /etc/resolv.conf, then the domain name can be resolved normally.

[root@localhost ~]# vi /etc/NetworkManager/NetworkManager.conf
[main]
plugins=ifcfg-rh
dns=none

2) Local host mapping file

  • The /etc/hosts file records a table of mapping relationships between host names and IP addresses, which are generally used to store information about hosts that are frequently accessed. When accessing an unknown domain name, first check whether there is a corresponding mapping record in the file, and if not, then query the DNS server.
  • For some websites that are frequently visited, you can reduce the DNS query process by adding correct mapping records in the /etc/hosts file, thereby increasing the Internet speed. Of course, if the wrong mapping record is added, it may cause abnormal website access. In addition, because the hosts file is only stored locally, the mapping record in it is only applicable to the current host, and cannot be applied to the entire network.

[root@localhost ~]# vim /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 The
format is IP address domain name or IP address host name
192.168.20.5 www.wodejia .com
192.168.20.55 node1

Guess you like

Origin blog.csdn.net/wulimingde/article/details/109442363