Ubuntu Server服务器网络配置方法及网络配置文件详解
由于服务器一般是没有桌面的,本文介绍采用命令方式进行Ubuntu Server服务器网络配置的方法,主要是更改Ubuntu Server服务器的网络配置文件。
1、网络配置文件/etc/network/interfaces
对所有网卡的配置,基本上都在/etc/network/interfaces这个文件中。如果你的Ubuntu Server服务器安装时是按照通过DHCP来获取IP地址进行设置的,默认的interfaces文件看起来应该像这样:
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
# The loopback network interface
auto lo
iface lo inet loopback
# The primary network interface
auto eth0
iface eth0 inet dhcp
其中,设备lo是TCP/IP定义的loopback虚拟网络设备,使得TCP/IP能够以127.0.0.1这个IP地址(主机名一般为localhost)来访问自身。eth0是第一块网卡,如果你有多块网卡,将依次是eth1、eth2等。
上述配置中的auto关键字,使得网络设备在系统启动时会自动启动。iface是interface的缩写,意为“接口”设备。而dhcp意思就是说,该网络设备要通过DHCP来获取IP配置信息。如果要手动指定IP地址等信息,则要把dhcp关键字改为static,如下:
auto eth0
iface eth0 inet static
address 192.168.1.10
netmask 255.255.255.0
gateway 192.168.1.1
其中,address关键字指定IP地址,netmask指定子网掩码,gateway指定网关。文件配置好后,需要重新启动网络以使其生效:
$ sudo /etc/init.d/networking restart
如果你要单独控制某块网卡,则可以使用ifdown、ifup命令:
$ sudo ifdown eth0
$ sudo ifup eth0
2、域名服务器配置文件/etc/resolv.conf
在Ubuntu中域名服务器(DNS)是在/etc/resolv.conf中配置的,它的格式如下:
search localdomain
nameserver 192.168.1.1
nameserver 202.102.14.68
其中的search命令会让系统首先在你的本地域中搜索主机,如果你有自己的DNS服务器,则可以把它写在这里。
3、/etc/hosts文件
如果你没有自己的DNS服务器,或者某些主机没有在你的DNS服务器注册,那么你可以把它们的主机名和IP地址写在/etc/hosts文件中,这样就可以解决这些主机的域名解析的问题了。
默认的/etc/hosts文件内容如下:
127.0.0.1 localhost
127.0.1.1 ubuntu.localdomain ubuntu
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
在默认情况下,在进行域名解析时,系统会首先来查找/etc/hosts文件,然后才去查询DNS服务器。如果你想更改这个顺序,则可以修改/etc/nsswitch.conf文件中hosts一行的顺序。
4、TCP/IP协议配置
在Ubuntu中,TCP/IP协议的所有信息除了“域名服务器地址”是在/etc/resolv.conf中配置的以外, 其他所有的项目都是在/etc/network/interfaces文件中配置的。
要查看TCP/IP配置情况,我们一般使用ifconfig命令,运行此命令可以查看所有网卡的配置情况。
5、NTP时间同步
Ubuntu在每次启动时都会自动到ntp.ubuntu.com去做时间同步,但是,由于服务器一般不会频繁启动,所以还是不能避免时间偏差。而且这个偏差可能很大,因此,我们需要对服务器的时间进行修正。最方便的方法是借助cron的计划任务,每天进行一次时间同步。比如创建一个文件/etc/cron.daily/timeupdate:
$ sudo nano /etc/cron.daily/timeupdate
然后输入以下内容:
ntpdate ntp.ubuntu.com
保存文件后赋予其可执行权限:
$ sudo chmod 755 /etc/cron.daily/timeupdate
这样,系统就可以每天去ntp.ubuntu.com获取时间(/etc/cron.daily/目录下的所有任务都会被每天执行一次),并校准服务器本身的时间。如果你担心时间获取失败,则可以将多个NTP服务器添加到/etc/cron.daily/timeupdate文件中:
ntpdate ntp.ubuntu.com pool.ntp.org
参考文献
【1】 冷罡华,《Ubuntu Server最佳方案》