1.加电开机
2.加载BIOS,加载CMOS,取得硬件配置,进行BIOS开机自检
3.通过引导装载程序选择要启动的操作系统,并且加载相应内核文件。
4.将内核解压到内存,由内核再次检测硬件,加载硬件驱动。
5.挂载根目录。
6.运行系统的第一个进程/etc/init。
7.读取/etc/init/目录下的配置文件。
8.获取系统默认的执行等级(通过/etc/init/start-ttys.conf这个配置文件)
9.进行系统初始化(通过/etc/rc.d/rc.sysinit这个配置文件)
10.开启对应级别需要开启的服务,关闭对应级别需要关闭的服务(通过/etc/rc.d/rc命令取得相应运行级别的服务是开启还是关闭(配置文件位于/etc/rc.d/rc#.d目录下))
11.运行用户自定义开机脚本/erc/rc.d/rc.local。
12.启动字符终端,启动图形终端(通过/erc/init/prefdm.conf文件)
#!/bin/bash # # /etc/rc.d/rc.sysinit - run once at boot time # # Taken in part from Miquel van Smoorenburg's bcheckrc. # HOSTNAME=$(/bin/hostname) #初始化主机名 set -m if [ -f /etc/sysconfig/network ]; then . /etc/sysconfig/network #取得网络环境 fi if [ -z "$HOSTNAME" -o "$HOSTNAME" = "(none)" ]; then HOSTNAME=localhost #如果HOSTNAME变量的值为空或没有内容,则将localhost设置为默认值 fi if [ ! -e /proc/mounts ]; then mount -n -t proc /proc /proc #测试与挂载内存设备/proc mount -n -t sysfs /sys /sys >/dev/null 2>&1 fi if [ ! -d /proc/bus/usb ]; then modprobe usbcore >/dev/null 2>&1 && mount -n -t usbfs /proc/bus/usb /proc/bus/usb else mount -n -t usbfs /proc/bus/usb /proc/bus/usb fi #remount /dev/shm to set attributes from fstab #669700 mount -n -o remount /dev/shm >/dev/null 2>&1 #remount /proc to set attributes from fstab #984003 mount -n -o remount /proc >/dev/null 2>&1 . /etc/init.d/functions PLYMOUTH= [ -x /bin/plymouth ] && PLYMOUTH=yes # Check SELinux status #是否开启SElinux SELINUX_STATE= if [ -e "/selinux/enforce" ] && [ "$(cat /proc/self/attr/current)" != "kernel" ]; then if [ -r "/selinux/enforce" ] ; then SELINUX_STATE=$(cat "/selinux/enforce") else # assume enforcing if you can't read it SELINUX_STATE=1 fi fi if [ -n "$SELINUX_STATE" -a -x /sbin/restorecon ] && __fgrep " /dev " /proc/mounts >/dev/null 2>&1 ; then /sbin/restorecon -R -F /dev 2>/dev/null fi disable_selinux() { echo $"*** Warning -- SELinux is active" echo $"*** Disabling security enforcement for system recovery." echo $"*** Run 'setenforce 1' to reenable." echo "0" > "/selinux/enforce" } relabel_selinux() { # if /sbin/init is not labeled correctly this process is running in the # wrong context, so a reboot will be required after relabel AUTORELABEL= . /etc/selinux/config echo "0" > /selinux/enforce [ -n "$PLYMOUTH" ] && plymouth --hide-splash if [ "$AUTORELABEL" = "0" ]; then echo echo $"*** Warning -- SELinux ${SELINUXTYPE} policy relabel is required. " echo $"*** /etc/selinux/config indicates you want to manually fix labeling" echo $"*** problems. Dropping you to a shell; the system will reboot" echo $"*** when you leave the shell." start rcS-emergency else echo echo $"*** Warning -- SELinux ${SELINUXTYPE} policy relabel is required." echo $"*** Relabeling could take a very long time, depending on file" echo $"*** system size and speed of hard drives." /sbin/fixfiles -F restore > /dev/null 2>&1 fi rm -f /.autorelabel echo $"Unmounting file systems" umount -a mount -n -o remount,ro / echo $"Automatic reboot in progress." reboot -f } # Print a text banner. #设置欢迎界面 echo -en $"\t\tWelcome to " read -r system_release < /etc/system-release if [[ "$system_release" == *"Red Hat"* ]]; then [ "$BOOTUP" = "color" ] && echo -en "\\033[0;31m" echo -en "Red Hat" [ "$BOOTUP" = "color" ] && echo -en "\\033[0;39m" PRODUCT=$(sed "s/Red Hat \(.*\) release.*/\1/" /etc/system-release) echo " $PRODUCT" elif [[ "$system_release" == *Fedora* ]]; then [ "$BOOTUP" = "color" ] && echo -en "\\033[0;34m" echo -en "Fedora" [ "$BOOTUP" = "color" ] && echo -en "\\033[0;39m" PRODUCT=$(sed "s/Fedora \(.*\) \?release.*/\1/" /etc/system-release) echo " $PRODUCT" elif [[ "$system_release" =~ "CentOS" ]]; then [ "$BOOTUP" = "color" ] && echo -en "\\033[0;36m" echo -en "CentOS" [ "$BOOTUP" = "color" ] && echo -en "\\033[0;39m" PRODUCT=$(sed "s/CentOS \(.*\) \?release.*/\1/" /etc/system-release) echo " $PRODUCT" else PRODUCT=$(sed "s/ release.*//g" /etc/system-release) echo "$PRODUCT" fi # Only read this once. cmdline=$(cat /proc/cmdline) # Initialize hardware #初始化硬件,接口设备的检测与PnP参数的测试 if [ -f /proc/sys/kernel/modprobe ]; then if ! strstr "$cmdline" nomodules && [ -f /proc/modules ] ; then sysctl -w kernel.modprobe="/sbin/modprobe" >/dev/null 2>&1 else # We used to set this to NULL, but that causes 'failed to exec' messages" sysctl -w kernel.modprobe="/bin/true" >/dev/null 2>&1 fi fi touch /dev/.in_sysinit >/dev/null 2>&1 # Set default affinity # if [ -x /bin/taskset ]; then if strstr "$cmdline" default_affinity= ; then for arg in $cmdline ; do if [ "${arg##default_affinity=}" != "${arg}" ]; then /bin/taskset -p ${arg##default_affinity=} 1 fi done fi fi nashpid=$(pidof nash 2>/dev/null) [ -n "$nashpid" ] && kill $nashpid >/dev/null 2>&1 unset nashpid /sbin/start_udev # Load other user-defined modules #加载用户自定义模块 for file in /etc/sysconfig/modules/*.modules ; do [ -x $file ] && $file done # Load modules (for backward compatibility with VARs) if [ -f /etc/rc.modules ]; then /etc/rc.modules fi mount -n /dev/pts >/dev/null 2>&1 [ -n "$SELINUX_STATE" ] && restorecon -F /dev/pts >/dev/null 2>&1 # Configure kernel parameters #配置内核参数 update_boot_stage RCkernelparam apply_sysctl # Set the hostname. update_boot_stage RChostname action $"Setting hostname ${HOSTNAME}: " hostname ${HOSTNAME} [ -n "${NISDOMAIN}" ] && domainname ${NISDOMAIN} # Sync waiting for storage. { rmmod scsi_wait_scan ; modprobe scsi_wait_scan ; rmmod scsi_wait_scan ; } >/dev/null 2>&1 # Device mapper & related initialization if ! __fgrep "device-mapper" /proc/devices >/dev/null 2>&1 ; then modprobe dm-mod >/dev/null 2>&1 fi if [ -f /etc/crypttab ]; then init_crypto 0 fi if ! strstr "$cmdline" nompath && [ -f /etc/multipath.conf -a \ -x /sbin/multipath ]; then modprobe dm-multipath > /dev/null 2>&1 /sbin/multipath -v 0 if [ -x /sbin/kpartx ]; then /sbin/dmsetup ls --target multipath --exec "/sbin/kpartx -a -p p" >/dev/null fi fi if ! strstr "$cmdline" nodmraid && [ -x /sbin/dmraid ]; then modprobe dm-mirror >/dev/null 2>&1 dmraidsets=$(LC_ALL=C /sbin/dmraid -s -c -i) if [ "$?" = "0" ]; then for dmname in $dmraidsets; do if [[ "$dmname" == isw_* ]] && \ ! strstr "$cmdline" noiswmd; then continue fi /sbin/dmraid -ay -i --rm_partitions -p "$dmname" >/dev/null 2>&1 /sbin/kpartx -a -p p "/dev/mapper/$dmname" done fi fi # Start any MD RAID arrays that haven't been started yet #初始化软件磁盘阵列 [ -r /proc/mdstat -a -r /dev/md/md-device-map ] && /sbin/mdadm -IRs if [ -x /sbin/lvm ]; then if [ ! -f /.nolvm ] && ! strstr "$cmdline" nolvm ; then action $"Setting up Logical Volume Management:" /sbin/lvm vgchange -a ay --sysinit else echo $"Logical Volume Management disabled at boot." fi fi if [ -f /etc/crypttab ]; then init_crypto 0 fi if [ -f /fastboot ] || strstr "$cmdline" fastboot ; then fastboot=yes fi if [ -f /fsckoptions ]; then fsckoptions=$(cat /fsckoptions) fi if [ -f /forcefsck ] || strstr "$cmdline" forcefsck ; then fsckoptions="-f $fsckoptions" elif [ -f /.autofsck ]; then [ -f /etc/sysconfig/autofsck ] && . /etc/sysconfig/autofsck if [ "$AUTOFSCK_DEF_CHECK" = "yes" ]; then AUTOFSCK_OPT="$AUTOFSCK_OPT -f" fi if [ -n "$AUTOFSCK_SINGLEUSER" ]; then [ -n "$PLYMOUTH" ] && plymouth --hide-splash echo echo $"*** Warning -- the system did not shut down cleanly. " echo $"*** Dropping you to a shell; the system will continue" echo $"*** when you leave the shell." [ -n "$SELINUX_STATE" ] && echo "0" > /selinux/enforce start rcS-emergency [ -n "$SELINUX_STATE" ] && echo "1" > /selinux/enforce [ -n "$PLYMOUTH" ] && plymouth --show-splash fi fsckoptions="$AUTOFSCK_OPT $fsckoptions" fi if [ "$BOOTUP" = "color" ]; then fsckoptions="-C $fsckoptions" else fsckoptions="-V $fsckoptions" fi READONLY= if [ -f /etc/sysconfig/readonly-root ]; then . /etc/sysconfig/readonly-root fi if strstr "$cmdline" readonlyroot ; then READONLY=yes [ -z "$RW_MOUNT" ] && RW_MOUNT=/var/lib/stateless/writable [ -z "$STATE_MOUNT" ] && STATE_MOUNT=/var/lib/stateless/state fi if strstr "$cmdline" noreadonlyroot ; then READONLY=no fi if [ "$READONLY" = "yes" -o "$TEMPORARY_STATE" = "yes" ]; then mount_empty() { if [ -e "$1" ]; then echo "$1" | cpio -p -vd "$RW_MOUNT" &>/dev/null mount -n --bind "$RW_MOUNT$1" "$1" fi } mount_dirs() { if [ -e "$1" ]; then mkdir -p "$RW_MOUNT$1" find "$1" -type d -print0 | cpio -p -0vd "$RW_MOUNT" &>/dev/null mount -n --bind "$RW_MOUNT$1" "$1" fi } mount_files() { if [ -e "$1" ]; then cp -a --parents "$1" "$RW_MOUNT" mount -n --bind "$RW_MOUNT$1" "$1" fi } # Common mount options for scratch space regardless of # type of backing store mountopts= # Scan partitions for local scratch storage rw_mount_dev=$(blkid -t LABEL="$RW_LABEL" -l -o device) # First try to mount scratch storage from /etc/fstab, then any # partition with the proper label. If either succeeds, be sure # to wipe the scratch storage clean. If both fail, then mount # scratch storage via tmpfs. if mount $mountopts "$RW_MOUNT" > /dev/null 2>&1 ; then rm -rf "$RW_MOUNT" > /dev/null 2>&1 elif [ x$rw_mount_dev != x ] && mount $rw_mount_dev $mountopts "$RW_MOUNT" > /dev/null 2>&1; then rm -rf "$RW_MOUNT" > /dev/null 2>&1 else mount -n -t tmpfs $RW_OPTIONS $mountopts none "$RW_MOUNT" fi for file in /etc/rwtab /etc/rwtab.d/* /dev/.initramfs/rwtab ; do is_ignored_file "$file" && continue [ -f $file ] && cat $file | while read type path ; do case "$type" in empty) mount_empty $path ;; files) mount_files $path ;; dirs) mount_dirs $path ;; *) ;; esac [ -n "$SELINUX_STATE" -a -e "$path" ] && restorecon -R "$path" done done # Use any state passed by initramfs [ -d /dev/.initramfs/state ] && cp -a /dev/.initramfs/state/* $RW_MOUNT # In theory there should be no more than one network interface active # this early in the boot process -- the one we're booting from. # Use the network address to set the hostname of the client. This # must be done even if we have local storage. ipaddr= if [ "$HOSTNAME" = "localhost" -o "$HOSTNAME" = "localhost.localdomain" ]; then ipaddr=$(ip addr show to 0.0.0.0/0 scope global | awk '/[[:space:]]inet / { print gensub("/.*","","g",$2) }') for ip in $ipaddr ; do HOSTNAME= eval $(ipcalc -h $ip 2>/dev/null) [ -n "$HOSTNAME" ] && { hostname ${HOSTNAME} ; break; } done fi # Clients with read-only root filesystems may be provided with a # place where they can place minimal amounts of persistent # state. SSH keys or puppet certificates for example. # # Ideally we'll use puppet to manage the state directory and to # create the bind mounts. However, until that's all ready this # is sufficient to build a working system. # First try to mount persistent data from /etc/fstab, then any # partition with the proper label, then fallback to NFS state_mount_dev=$(blkid -t LABEL="$STATE_LABEL" -l -o device) if mount $mountopts $STATE_OPTIONS "$STATE_MOUNT" > /dev/null 2>&1 ; then /bin/true elif [ x$state_mount_dev != x ] && mount $state_mount_dev $mountopts "$STATE_MOUNT" > /dev/null 2>&1; then /bin/true elif [ ! -z "$CLIENTSTATE" ]; then # No local storage was found. Make a final attempt to find # state on an NFS server. mount -t nfs $CLIENTSTATE/$HOSTNAME $STATE_MOUNT -o rw,nolock fi if [ -w "$STATE_MOUNT" ]; then mount_state() { if [ -e "$1" ]; then [ ! -e "$STATE_MOUNT$1" ] && cp -a --parents "$1" "$STATE_MOUNT" mount -n --bind "$STATE_MOUNT$1" "$1" fi } for file in /etc/statetab /etc/statetab.d/* ; do is_ignored_file "$file" && continue [ ! -f "$file" ] && continue if [ -f "$STATE_MOUNT/$file" ] ; then mount -n --bind "$STATE_MOUNT/$file" "$file" fi for path in $(grep -v "^#" "$file" 2>/dev/null); do mount_state "$path" [ -n "$SELINUX_STATE" -a -e "$path" ] && restorecon -R "$path" done done if [ -f "$STATE_MOUNT/files" ] ; then for path in $(grep -v "^#" "$STATE_MOUNT/files" 2>/dev/null); do mount_state "$path" [ -n "$SELINUX_STATE" -a -e "$path" ] && restorecon -R "$path" done fi fi fi if [[ " $fsckoptions" != *" -y"* ]]; then fsckoptions="-a $fsckoptions" fi _RUN_QUOTACHECK=0 if [ -f /forcequotacheck ] || strstr "$cmdline" forcequotacheck ; then _RUN_QUOTACHECK=1 fi if [ -z "$fastboot" -a "$READONLY" != "yes" ]; then STRING=$"Checking filesystems" echo $STRING fsck -T -t noopts=_netdev -A $fsckoptions rc=$? if [ "$rc" -eq "0" ]; then success "$STRING" echo elif [ "$rc" -eq "1" ]; then passed "$STRING" echo elif [ "$rc" -eq "2" -o "$rc" -eq "3" ]; then echo $"Unmounting file systems" umount -a mount -n -o remount,ro / echo $"Automatic reboot in progress." reboot -f fi # A return of 4 or higher means there were serious problems. if [ $rc -gt 1 ]; then [ -n "$PLYMOUTH" ] && plymouth --hide-splash failure "$STRING" echo echo echo $"*** An error occurred during the file system check." echo $"*** Dropping you to a shell; the system will reboot" echo $"*** when you leave the shell." str=$"(Repair filesystem)" PS1="$str \# # "; export PS1 [ "$SELINUX_STATE" = "1" ] && disable_selinux start rcS-emergency echo $"Unmounting file systems" umount -a mount -n -o remount,ro / echo $"Automatic reboot in progress." reboot -f elif [ "$rc" -eq "1" ]; then _RUN_QUOTACHECK=1 fi fi remount_needed() { local state oldifs [ "$READONLY" = "yes" ] && return 1 state=$(LC_ALL=C awk '/ \/ / && ($3 !~ /rootfs/) { print $4 }' /proc/mounts) oldifs=$IFS IFS="," for opt in $state ; do if [ "$opt" = "rw" ]; then IFS=$oldifs return 1 fi done IFS=$oldifs return 0 } # Remount the root filesystem read-write. update_boot_stage RCmountfs if remount_needed ; then action $"Remounting root filesystem in read-write mode: " mount -n -o remount,rw / fi # Clean up SELinux labels if [ -n "$SELINUX_STATE" ]; then restorecon /etc/mtab /etc/ld.so.cache /etc/blkid/blkid.tab /etc/resolv.conf >/dev/null 2>&1 fi # If relabeling, relabel mount points. if [ -n "$SELINUX_STATE" -a "$READONLY" != "yes" ]; then if [ -f /.autorelabel ] || strstr "$cmdline" autorelabel ; then restorecon $(awk '!/^#/ && $4 !~ /noauto/ && $2 ~ /^\// { print $2 }' /etc/fstab) >/dev/null 2>&1 fi fi if [ "$READONLY" != "yes" ] ; then # Clear mtab (> /etc/mtab) &> /dev/null # Remove stale backups rm -f /etc/mtab~ /etc/mtab~~ # Enter mounted filesystems into /etc/mtab mount -f / mount -f /proc >/dev/null 2>&1 mount -f /sys >/dev/null 2>&1 mount -f /dev/pts >/dev/null 2>&1 mount -f /dev/shm >/dev/null 2>&1 mount -f /proc/bus/usb >/dev/null 2>&1 fi # Mount all other filesystems (except for NFS and /proc, which is already # mounted). Contrary to standard usage, # filesystems are NOT unmounted in single user mode. # The 'no' applies to all listed filesystem types. See mount(8). if [ "$READONLY" != "yes" ] ; then action $"Mounting local filesystems: " mount -a -t nonfs,nfs4,smbfs,ncpfs,cifs,gfs,gfs2 -O no_netdev else action $"Mounting local filesystems: " mount -a -n -t nonfs,nfs4,smbfs,ncpfs,cifs,gfs,gfs2 -O no_netdev fi # Update quotas if necessary if [ X"$_RUN_QUOTACHECK" = X1 -a -x /sbin/quotacheck ]; then action $"Checking local filesystem quotas: " /sbin/quotacheck -anug fi if [ -x /sbin/quotaon ]; then action $"Enabling local filesystem quotas: " /sbin/quotaon -aug fi # Check to see if a full relabel is needed if [ -n "$SELINUX_STATE" -a "$READONLY" != "yes" ]; then if [ -f /.autorelabel ] || strstr "$cmdline" autorelabel ; then relabel_selinux fi else if [ -d /etc/selinux -a "$READONLY" != "yes" ]; then [ -f /.autorelabel ] || touch /.autorelabel fi fi # Initialize pseudo-random number generator if [ -f "/var/lib/random-seed" ]; then cat /var/lib/random-seed > /dev/urandom else [ "$READONLY" != "yes" ] && touch /var/lib/random-seed fi if [ "$READONLY" != "yes" ]; then chmod 600 /var/lib/random-seed dd if=/dev/urandom of=/var/lib/random-seed count=1 bs=512 2>/dev/null fi if [ -f /etc/crypttab ]; then init_crypto 1 fi # Configure machine if necessary. if [ -f /.unconfigured ]; then if [ -x /bin/plymouth ]; then /bin/plymouth quit fi if [ -x /usr/bin/system-config-keyboard ]; then /usr/bin/system-config-keyboard fi if [ -x /usr/bin/passwd ]; then /usr/bin/passwd root fi if [ -x /usr/sbin/system-config-network-tui ]; then /usr/sbin/system-config-network-tui fi if [ -x /usr/sbin/timeconfig ]; then /usr/sbin/timeconfig fi if [ -x /usr/sbin/authconfig-tui ]; then /usr/sbin/authconfig-tui --nostart fi if [ -x /usr/sbin/ntsysv ]; then /usr/sbin/ntsysv --level 35 fi # Reread in network configuration data. if [ -f /etc/sysconfig/network ]; then . /etc/sysconfig/network # Reset the hostname. action $"Resetting hostname ${HOSTNAME}: " hostname ${HOSTNAME} fi rm -f /.unconfigured fi # Clean out /. #清理操作 rm -f /fastboot /fsckoptions /forcefsck /.autofsck /forcequotacheck /halt \ /poweroff /.suspended &> /dev/null # Do we need (w|u)tmpx files? We don't set them up, but the sysadmin might... _NEED_XFILES= [ -f /var/run/utmpx -o -f /var/log/wtmpx ] && _NEED_XFILES=1 # Clean up /var. #清理操作 rm -rf /var/lock/cvs/* /var/run/screen/* find /var/lock /var/run ! -type d -exec rm -f {} \; rm -f /var/lib/rpm/__db* &> /dev/null rm -f /var/gdm/.gdmfifo &> /dev/null [ "$PROMPT" != no ] && plymouth watch-keystroke --command "touch /var/run/confirm" --keys=Ii & # Clean up utmp/wtmp #清理操作 > /var/run/utmp touch /var/log/wtmp chgrp utmp /var/run/utmp /var/log/wtmp chmod 0664 /var/run/utmp /var/log/wtmp if [ -n "$_NEED_XFILES" ]; then > /var/run/utmpx touch /var/log/wtmpx chgrp utmp /var/run/utmpx /var/log/wtmpx chmod 0664 /var/run/utmpx /var/log/wtmpx fi [ -n "$SELINUX_STATE" ] && restorecon /var/run/utmp* /var/log/wtmp* >/dev/null 2>&1 # Clean up various /tmp bits #清理操作 [ -n "$SELINUX_STATE" ] && restorecon /tmp rm -f /tmp/.X*-lock /tmp/.lock.* /tmp/.gdm_socket /tmp/.s.PGSQL.* rm -rf /tmp/.X*-unix /tmp/.ICE-unix /tmp/.font-unix /tmp/hsperfdata_* \ /tmp/kde-* /tmp/ksocket-* /tmp/mc-* /tmp/mcop-* /tmp/orbit-* \ /tmp/scrollkeeper-* /tmp/ssh-* \ /dev/.in_sysinit # Make ICE directory mkdir -m 1777 -p /tmp/.ICE-unix >/dev/null 2>&1 chown root:root /tmp/.ICE-unix [ -n "$SELINUX_STATE" ] && restorecon /tmp/.ICE-unix >/dev/null 2>&1 # Start up swapping. #激活交换分区 update_boot_stage RCswap action $"Enabling /etc/fstab swaps: " swapon -a -e if [ "$AUTOSWAP" = "yes" ]; then curswap=$(awk '/^\/dev/ { print $1 }' /proc/swaps | while read x; do get_numeric_dev dec $x ; echo -n " "; done) swappartitions=$(blkid -t TYPE=swap -o device) if [ x"$swappartitions" != x ]; then for partition in $swappartitions ; do [ ! -e $partition ] && continue majmin=$(get_numeric_dev dec $partition) echo $curswap | grep -qw "$majmin" || action $"Enabling local swap partitions: " swapon $partition done fi fi # Set up binfmt_misc /bin/mount -t binfmt_misc none /proc/sys/fs/binfmt_misc > /dev/null 2>&1 # Boot time profiles. Yes, this should be somewhere else. if [ -x /usr/sbin/system-config-network-cmd ]; then if strstr "$cmdline" netprofile= ; then for arg in $cmdline ; do if [ "${arg##netprofile=}" != "${arg}" ]; then /usr/sbin/system-config-network-cmd --profile ${arg##netprofile=} fi done fi fi # Now that we have all of our basic modules loaded and the kernel going, # let's dump the syslog ring somewhere so we can find it later [ -f /var/log/dmesg ] && mv -f /var/log/dmesg /var/log/dmesg.old dmesg -s 131072 > /var/log/dmesg # create the crash indicator flag to warn on crashes, offer fsck with timeout touch /.autofsck &> /dev/null [ "$PROMPT" != no ] && plymouth --ignore-keystroke=Ii if strstr "$cmdline" confirm ; then touch /var/run/confirm fi # Let rhgb know that we're leaving rc.sysinit if [ -x /bin/plymouth ]; then /bin/plymouth --sysinit fi
/etc/rc.d/sysinit脚本的功能可以概括如下:
设定主机名:读取/etc/sysconfig/network文件中的HOSTNAME参数,并以之设定主机名 打印文本欢迎信息 激活SELinux和udev 挂载/etc/fstab文件中定义的其它文件系统 激活swap 检测根文件系统,并以读写方式重新挂载; 设置系统时钟 根据/etc/sysctl.conf设置内核参数 激活LVM和RAID设备; 加载额外设备的驱动程序; 清理操作
sed是一种轻量级的流编辑器,sed是主要用来对数据进行选取、替换、删除、新增的命令。
sed命令常用选项:
-n:只输出经过sed编辑的内容 -e:允许对输入的数据运用多条sed命令进行编辑 -i:直接修改源文件,而不是输出至屏幕 -r: 支持使用扩展正则表达式 -f 文件路径:从指定文件中读取要编辑的内容
sed的语法:
sed 选项 '动作' 文件名
sed的工作原理: sed流编辑器的原理是将需要编辑的内容读取到内存中,在经过相应的动作处理后,输出至屏幕。
存放sed将要编辑的内容的那部分内存我们可以称为模式空间。
sed的一般动作:
d: 删除,删除指定的行 p: 显示模式空间中的内容 a \text:在行后面追加文本;支持使用\n实现多行追加; i \text:在行前面插入文本;支持使用\n实现多行插入; c \text:替换行为单行或多行文本; w 文件路径: 保存模式空间匹配到的行至指定文件中; r 文件路径:读取指定文件的文本流至模式空间中匹配到的行的行后; =: 为模式空间中的行打印行号; !: 取反条件; s///:支持使用其它分隔符,s@@@,s###; 替换标记: g: 行内全局替换; p: 显示替换成功的行; w 文件路径:将替换成功的结果保存至指定文件中;
范例:使用sed命令将/etc/yum.conf中的第二行显示到屏幕
[root@tomshen etc]# cd [root@tomshen ~]# sed -n '2p' /etc/yum.conf cachedir=/var/cache/yum/$basearch/$releasever [root@tomshen ~]#
这里我们使用了-n 选项只显示在模式空间中经过编辑的内容。
如果我们不使用-n选项,则编辑过和没有编辑过的内容都会显示。
[root@tomshen ~]# sed '2p' /etc/yum.conf [main] cachedir=/var/cache/yum/$basearch/$releasever cachedir=/var/cache/yum/$basearch/$releasever #因为都显示,故而第二行内容重复显示 keepcache=0 debuglevel=2 logfile=/var/log/yum.log exactarch=1 obsoletes=1 gpgcheck=1 plugins=1 installonly_limit=5 bugtracker_url=http://bugs.centos.org/set_project.php?project_id=16&ref=http://bugs.centos.org/bug_report_page.php?category=yum distroverpkg=centos-release # This is the default, if you make this bigger yum won't see if the metadata # is newer on the remote and so you'll "gain" the bandwidth of not having to # download the new metadata and "pay" for it by yum not having correct # information. # It is esp. important, to have correct metadata, for distributions like # Fedora which don't keep old packages around. If you don't like this checking # interupting your command line usage, it's much better to have something # manually check the metadata once an hour (yum-updatesd will do this). # metadata_expire=90m # PUT YOUR REPOS HERE OR IN separate files named file.repo # in /etc/yum.repos.d [root@tomshen ~]#
范例:在/etc/yum.conf的第二行后面添加一行新内容
[root@tomshen ~]# sed -n '2a\新的行' /etc/yum.conf 新的行 [root@tomshen ~]# sed '2a\新的行' /etc/yum.conf [main] cachedir=/var/cache/yum/$basearch/$releasever 新的行 keepcache=0 debuglevel=2 logfile=/var/log/yum.log exactarch=1 obsoletes=1 gpgcheck=1 plugins=1 installonly_limit=5 bugtracker_url=http://bugs.centos.org/set_project.php?project_id=16&ref=http://bugs.centos.org/bug_report_page.php?category=yum distroverpkg=centos-release # This is the default, if you make this bigger yum won't see if the metadata # is newer on the remote and so you'll "gain" the bandwidth of not having to # download the new metadata and "pay" for it by yum not having correct # information. # It is esp. important, to have correct metadata, for distributions like # Fedora which don't keep old packages around. If you don't like this checking # interupting your command line usage, it's much better to have something # manually check the metadata once an hour (yum-updatesd will do this). # metadata_expire=90m # PUT YOUR REPOS HERE OR IN separate files named file.repo # in /etc/yum.repos.d [root@tomshen ~]#
范例:在/etc/yum.conf的第二行前面添加一行新内容
[root@tomshen ~]# sed -n '2i\行前面新的行' /etc/yum.conf 行前面新的行 [root@tomshen ~]# sed '2i\行前面新的行' /etc/yum.conf [main] 行前面新的行 cachedir=/var/cache/yum/$basearch/$releasever keepcache=0 debuglevel=2 logfile=/var/log/yum.log exactarch=1 obsoletes=1 gpgcheck=1 plugins=1 installonly_limit=5 bugtracker_url=http://bugs.centos.org/set_project.php?project_id=16&ref=http://bugs.centos.org/bug_report_page.php?category=yum distroverpkg=centos-release # This is the default, if you make this bigger yum won't see if the metadata # is newer on the remote and so you'll "gain" the bandwidth of not having to # download the new metadata and "pay" for it by yum not having correct # information. # It is esp. important, to have correct metadata, for distributions like # Fedora which don't keep old packages around. If you don't like this checking # interupting your command line usage, it's much better to have something # manually check the metadata once an hour (yum-updatesd will do this). # metadata_expire=90m # PUT YOUR REPOS HERE OR IN separate files named file.repo # in /etc/yum.repos.d [root@tomshen ~]#
范例:将/etc/yum.conf第二行替换为新内容
[root@tomshen ~]# sed '2c\新的替换行' /etc/yum.conf [main] 新的替换行 keepcache=0 debuglevel=2 logfile=/var/log/yum.log exactarch=1 obsoletes=1 gpgcheck=1 plugins=1 installonly_limit=5 bugtracker_url=http://bugs.centos.org/set_project.php?project_id=16&ref=http://bugs.centos.org/bug_report_page.php?category=yum distroverpkg=centos-release # This is the default, if you make this bigger yum won't see if the metadata # is newer on the remote and so you'll "gain" the bandwidth of not having to # download the new metadata and "pay" for it by yum not having correct # information. # It is esp. important, to have correct metadata, for distributions like # Fedora which don't keep old packages around. If you don't like this checking # interupting your command line usage, it's much better to have something # manually check the metadata once an hour (yum-updatesd will do this). # metadata_expire=90m # PUT YOUR REPOS HERE OR IN separate files named file.repo # in /etc/yum.repos.d [root@tomshen ~]#
范例:删除/etc/yum.conf的第二行
[root@tomshen ~]# sed '2d' /etc/yum.conf [main] keepcache=0 debuglevel=2 logfile=/var/log/yum.log exactarch=1 obsoletes=1 gpgcheck=1 plugins=1 installonly_limit=5 bugtracker_url=http://bugs.centos.org/set_project.php?project_id=16&ref=http://bugs.centos.org/bug_report_page.php?category=yum distroverpkg=centos-release # This is the default, if you make this bigger yum won't see if the metadata # is newer on the remote and so you'll "gain" the bandwidth of not having to # download the new metadata and "pay" for it by yum not having correct # information. # It is esp. important, to have correct metadata, for distributions like # Fedora which don't keep old packages around. If you don't like this checking # interupting your command line usage, it's much better to have something # manually check the metadata once an hour (yum-updatesd will do this). # metadata_expire=90m # PUT YOUR REPOS HERE OR IN separate files named file.repo # in /etc/yum.repos.d [root@tomshen ~]#
范例:对/etc/yum.conf的第二行不做任何处理,保存至一个文件中
[root@tomshen ~]# sed -n '2wxinyum' /etc/yum.conf [root@tomshen ~]# ls abc.d bcd.e nohup.out xinyum 模板 下载 abcd.fgh cddd.e \root\ yuan 视频 音乐 abcd.txt install.log zhongzhi.sh 图片 桌面 anaconda-ks.cfg install.log.syslog sleep500.sh 公共的 文档 [root@tomshen ~]# cat xinyum cachedir=/var/cache/yum/$basearch/$releasever [root@tomshen ~]#
新建一文件,文件内容为“指定文件的文本流”,使用sed命令的r动作,将这个文件的内容插入到/etc/yum.conf的第二行后面
[root@tomshen ~]# vim sedtest [root@tomshen ~]# sed '2rsedtest' /etc/yum.conf [main] cachedir=/var/cache/yum/$basearch/$releasever 指定文件的文本流 keepcache=0 debuglevel=2 logfile=/var/log/yum.log exactarch=1 obsoletes=1 gpgcheck=1 plugins=1 installonly_limit=5 bugtracker_url=http://bugs.centos.org/set_project.php?project_id=16&ref=http://bugs.centos.org/bug_report_page.php?category=yum distroverpkg=centos-release # This is the default, if you make this bigger yum won't see if the metadata # is newer on the remote and so you'll "gain" the bandwidth of not having to # download the new metadata and "pay" for it by yum not having correct # information. # It is esp. important, to have correct metadata, for distributions like # Fedora which don't keep old packages around. If you don't like this checking # interupting your command line usage, it's much better to have something # manually check the metadata once an hour (yum-updatesd will do this). # metadata_expire=90m # PUT YOUR REPOS HERE OR IN separate files named file.repo # in /etc/yum.repos.d [root@tomshen ~]#
给/etc/yum.conf的一至十行添加行号
[root@tomshen ~]# sed '1,10=' /etc/yum.conf 1 [main] 2 cachedir=/var/cache/yum/$basearch/$releasever 3 keepcache=0 4 debuglevel=2 5 logfile=/var/log/yum.log 6 exactarch=1 7 obsoletes=1 8 gpgcheck=1 9 plugins=1 10 installonly_limit=5 bugtracker_url=http://bugs.centos.org/set_project.php?project_id=16&ref=http://bugs.centos.org/bug_report_page.php?category=yum distroverpkg=centos-release # This is the default, if you make this bigger yum won't see if the metadata # is newer on the remote and so you'll "gain" the bandwidth of not having to # download the new metadata and "pay" for it by yum not having correct # information. # It is esp. important, to have correct metadata, for distributions like # Fedora which don't keep old packages around. If you don't like this checking # interupting your command line usage, it's much better to have something # manually check the metadata once an hour (yum-updatesd will do this). # metadata_expire=90m # PUT YOUR REPOS HERE OR IN separate files named file.repo # in /etc/yum.repos.d [root@tomshen ~]#
将/etc/yum.conf中的所有的yum这个字符串替换为MYYUMTEST
[root@tomshen ~]# sed 's/yum/MYYUMTEST/g' /etc/yum.conf [main] cachedir=/var/cache/MYYUMTEST/$basearch/$releasever keepcache=0 debuglevel=2 logfile=/var/log/MYYUMTEST.log exactarch=1 obsoletes=1 gpgcheck=1 plugins=1 installonly_limit=5 bugtracker_url=http://bugs.centos.org/set_project.php?project_id=16&ref=http://bugs.centos.org/bug_report_page.php?category=MYYUMTEST distroverpkg=centos-release # This is the default, if you make this bigger MYYUMTEST won't see if the metadata # is newer on the remote and so you'll "gain" the bandwidth of not having to # download the new metadata and "pay" for it by MYYUMTEST not having correct # information. # It is esp. important, to have correct metadata, for distributions like # Fedora which don't keep old packages around. If you don't like this checking # interupting your command line usage, it's much better to have something # manually check the metadata once an hour (MYYUMTEST-updatesd will do this). # metadata_expire=90m # PUT YOUR REPOS HERE OR IN separate files named file.repo # in /etc/MYYUMTEST.repos.d [root@tomshen ~]#
在上面的范例中我们看到,输出的内容中符合上一个范例要求的内容和不符合的均输出了。
这里我们可以使用p这个替换标记,只显示替换成功的行。
[root@tomshen ~]# sed -n 's/yum/MYYUMTEST/p' /etc/yum.conf cachedir=/var/cache/MYYUMTEST/$basearch/$releasever logfile=/var/log/MYYUMTEST.log bugtracker_url=http://bugs.centos.org/set_project.php?project_id=16&ref=http://bugs.centos.org/bug_report_page.php?category=MYYUMTEST # This is the default, if you make this bigger MYYUMTEST won't see if the metadata # download the new metadata and "pay" for it by MYYUMTEST not having correct # manually check the metadata once an hour (MYYUMTEST-updatesd will do this). # in /etc/MYYUMTEST.repos.d [root@tomshen ~]#
在上面我们讲到过,sed流编辑器的原理是将需要编辑的内容读取到内存中,在经过相应的动作处理后,输出至屏幕。
我们把那块存放将要编辑的内容的内存称为模式空间,其实sed命令有时还会用到一块叫做保持空间(又称后备空间)的内存。
sed可以将在模式空间中处理过的内容送至保持空间中,而不是输出至屏幕。
h: 把模式空间中的内容覆盖至保持空间中; H:把模式空间中的内容追加至保持空间中; g: 从保持空间取出数据覆盖至模式空间; G:从保持空间取出内容追加至模式空间; x: 把模式空间中的内容与保持空间中的内容进行互换; n: 读取匹配到的行的下一行至模式空间; N:追加匹配到的行的下一行至模式空间; D:删除多行模式空间中的所有行;
范例:只显示oushu的偶数行
[root@tomshen ~]# cat oushu 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [root@tomshen ~]# sed -n 'n;p' oushu 2 4 6 8 10 12 14 [root@tomshen ~]#
范例:将testtxt中的一行内容,移到上一行结尾
[root@tomshen ~]# cat testtxt 我属猪 我属猴 我属龙 我属蛇 [root@tomshen ~]# sed '/龙/{N;s/\n//}' testtxt 我属猪 我属猴 我属龙我属蛇 [root@tomshen ~]# 范例:逆向显示oushu [root@tomshen ~]# sed '1!G;h;$!d' oushu 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 [root@tomshen ~]#
作为linux文本处理三剑客里最强悍的awk这个命令,它强大的离谱,因为awk不是一条简单命令它是一门语言。
下面就GNU版本的awk(既gawk)的简单用法做一下讲解。
我们以长格式查看一下awk这个命令,可以看到awk命令是gawk命令的软连接。
所以我们在使用awk命令时,awk和gawk的意义相同。
[root@tomshen ~]# ll /bin/awk lrwxrwxrwx. 1 root root 4 1月 3 21:21 /bin/awk -> gawk [root@tomshen ~]#
awk处理数据的方式是以行为一次处理的单位,具体将数据分成一个一个的"字段"来进行处理的。
awk的基本用法:
awk 选项 '条件a{动作a}条件b{动作b}....' 文件名 选项: -F:指明输入时用到的字段分隔符; -v 变量名=变量值: 自定义变量;
既然awk处理数据的方式是以行为一次处理的单位,具体将数据分成一个一个的"字段"来进行处理的。
那么awk是依据什么来分割“字段”的呢,这就要提到awk的内置变量了。
awk内置变量:
FS:输入域字段分割符,默认为空白字符
OFS:输出域字段分割符,默认为空白字符
RS:输入时的换行符
ORS:输出时的换行符
NF:每一行拥有的字段总数
NR:以处理的数据的行数
FNR:当用awk处理多个文件时,各个文件的行数
FILENAME:当前文件名
ARGC:命令行参数的个数
ARGV:数组,保存的是命令行所给定的各参数
如果要将awk编辑过的内容输出到屏幕上的话可使用格式化输出命令printf或者awk的子命令print。
printf命令可参考:
因为是具体将数据分成一个一个的"字段"来进行处理的,所以在awk命令中位置参数变量$1,$2,$3....就表示了一行中的第一个“字段”,第二个“字段”,第三个"字段"...
$0即表示整行
BEGIN{ 这里面放的是执行前的语句,仅在开始处理文件中的文本之前执行一次 } END {这里面放的是处理完所有的行后要执行的语句,仅在文本处理完成之后执行一次 }
{这里面放的是处理每一行时要执行的语句,重复执行}
由于awk不仅是一条命令更是一门语言,所以awk可以支持的“条件”非常非常多。如各种操作符,条件判断,循环语句,数组,函数....
-x +x: 转换为数值; 字符串操作符:没有符号的操作符,字符串连接 赋值操作符: =, +=, -=, *=, /=, %=, ^= ++, -- 比较操作符: >, >=, <, <=, !=, == 模式匹配符: ~:是否匹配 !~:是否不匹配 逻辑操作符: && || ! 函数调用: function_name(argu1, argu2, ...) 条件表达式: 条件表达式?条件表达式为真时要执行的语句:条件表达式为假时要执行的语句
范例输出当前目录内的文件总大小:
[root@tomshen ~]# ls -lh | awk '{sum+=$5}END{print sum}' 1455.9 [root@tomshen ~]#
在awk中如果要使用正则表达式的话需要使用“/"将正则表达式包起来 范例:报告/etc/yum.conf文件中的所有注释信息
[root@tomshen ~]# awk /^#/ /etc/yum.conf # # This is the default, if you make this bigger yum won't see if the metadata # is newer on the remote and so you'll "gain" the bandwidth of not having to # download the new metadata and "pay" for it by yum not having correct # information. # It is esp. important, to have correct metadata, for distributions like # Fedora which don't keep old packages around. If you don't like this checking # interupting your command line usage, it's much better to have something # manually check the metadata once an hour (yum-updatesd will do this). # metadata_expire=90m # PUT YOUR REPOS HERE OR IN separate files named file.repo # in /etc/yum.repos.d [root@tomshen ~]#
awk中可作为条件使用的控制语句:
if(判断条件) {要执行的语句} if(判断条件) {要执行的语句} else {要执行的语句 } while(判断条件) {循环体} do {循环体} while(判断条件) for(初始化;控制条件;增量) {循环体} break continue delete array[数组下标] delete array exit { statements }
可以看到在awk中的这些控制语句,其语法格式与一些主流的编程语言的控制语句语法格式已经非常相识甚至相同了。
不同于shell的奇葩的语法格式。
范例;输出当前系统UID小于等于100的用户的UID和用户名。
[root@tomshen ~]# awk -F: '{if($3<=100){printf " UID less than 100 of users list : UID:%i \t username: %s \n",$3,$1}}' /etc/passwd UID less than 100 of users list : UID:0 username: root UID less than 100 of users list : UID:1 username: bin UID less than 100 of users list : UID:2 username: daemon UID less than 100 of users list : UID:3 username: adm UID less than 100 of users list : UID:4 username: lp UID less than 100 of users list : UID:5 username: sync UID less than 100 of users list : UID:6 username: shutdown UID less than 100 of users list : UID:7 username: halt UID less than 100 of users list : UID:8 username: mail UID less than 100 of users list : UID:10 username: uucp UID less than 100 of users list : UID:11 username: operator UID less than 100 of users list : UID:12 username: games UID less than 100 of users list : UID:13 username: gopher UID less than 100 of users list : UID:14 username: ftp UID less than 100 of users list : UID:99 username: nobody UID less than 100 of users list : UID:81 username: dbus UID less than 100 of users list : UID:69 username: vcsa UID less than 100 of users list : UID:32 username: rpc UID less than 100 of users list : UID:29 username: rpcuser UID less than 100 of users list : UID:68 username: haldaemon UID less than 100 of users list : UID:42 username: gdm UID less than 100 of users list : UID:38 username: ntp UID less than 100 of users list : UID:48 username: apache UID less than 100 of users list : UID:89 username: postfix UID less than 100 of users list : UID:74 username: sshd UID less than 100 of users list : UID:72 username: tcpdump [root@tomshen ~]#
关联数组也可以作为awk的条件来使用,对于关联数组如果某数组元素事先不存在,在引用时,awk会自动创建此元素,并将其值初始化为“空串”。
使用for循环的一种特殊格式可遍历数组中的每个元素:
若要遍历数组中的每个元素,要使用for循环; for(变量名 in 数组名) {循环体}
范例:
[root@tomshen ~]# awk 'BEGIN{tom["a"]=123; tom["b"]=456; tom["c"]=789;for(i in tom){printf "Array subscript:%s,value :%i \n",i,tom[i]}}' Array subscript:a,value :123 Array subscript:b,value :456 Array subscript:c,value :789 [root@tomshen ~]#
上面我们直接在awk里定义一个数组,使用for循环的特殊格式遍历数组,然后输出其内容。
脚本一:
#!/bin/bash # this is a random number shell #Author:tomshen declare -a tomarray declare -a sort_array for((i=0;i<10;i++)) do name1=$(date +%N) tomarray[i]=$name1 done sort_array=($(for m in "${tomarray[@]}";do echo $m;done | sort)) echo " Sorted random number:${sort_array[@]}"
脚本二:
#!/bin/bash # this is a random number shell #Author:tomshen #version:2 for((i=0;isort_tom echo "Sorted random number:$(cat sort_tom | sort)"
[root@tomshen ~]# crontab -l */1 * * * * date >> /mnt/addpan/datelog.log 1-59/2 * * * * echo "基数***" >> /mnt/addpan/jishu.log 5 1 * * 2 /data/get_username.sh &> /tmp/get_username.log [root@tomshen ~]#
#!/bin/bash read -p "Please enter a directory: " diress if [ -d "$diress" ] then echo "$diress This directory exists " echo "Its content is:" ls $($diress) else if [ ! -d "$diress" ] then mkdir -pv $diress fi fi
#!/bin/bash for((i=1;i<10;i++));do for((m=1;m<=i;m++));do echo -e -n "${i}X${m}=$[$i*$m]\t" done echo done
运行效果:
[root@tomshen ~]# ./ifmolu.sh Please enter a directory: dfsfsdf mkdir: 已创建目录 "dfsfsdf" [root@tomshen ~]# ./ifmolu.sh Please enter a directory: /etc /etc This directory exists Its content is: ./ifmolu.sh: line 10: /etc: is a directory aaaaaaa anaconda-ks.cfg fsf52345345 install.log oushu \root\xinyum sort_tom yuan 视频 音乐 abc.d bcd.e hello install.log.syslog random_number2.sh sedtest test.s zhongzhi.sh 图片 桌面 abcd.fgh cddd.e ifmolu.sh jiujiu.sh random_number.sh shutest.txt testtxt 公共的 文档 abcd.txt dfsfsdf ifmolussssss.sh nohup.out \root\ sleep500.sh xinyum 模板 下载 [root@tomshen ~]#
根的区域解析库文件:
[root@tomshen ~]# cd /var/named [root@tomshen named]# ls data dynamic named.ca named.empty named.localhost named.loopback slaves [root@tomshen named]# cat named.ca #查看根的区域解析库文件 ; > DiG 9.9.4-P2-RedHat-9.9.4-12.P2 > +norec NS . @a.root-servers.net ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 26229 ;; flags: qr aa; QUERY: 1, ANSWER: 13, AUTHORITY: 0, ADDITIONAL: 24 ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags:; udp: 1472 ;; QUESTION SECTION: ;. IN NS ;; ANSWER SECTION: . 518400 IN NS a.root-servers.net. . 518400 IN NS b.root-servers.net. . 518400 IN NS c.root-servers.net. . 518400 IN NS d.root-servers.net. . 518400 IN NS e.root-servers.net. . 518400 IN NS f.root-servers.net. . 518400 IN NS g.root-servers.net. . 518400 IN NS h.root-servers.net. . 518400 IN NS i.root-servers.net. . 518400 IN NS j.root-servers.net. . 518400 IN NS k.root-servers.net. . 518400 IN NS l.root-servers.net. . 518400 IN NS m.root-servers.net. ;; ADDITIONAL SECTION: a.root-servers.net. 518400 IN A 198.41.0.4 b.root-servers.net. 518400 IN A 192.228.79.201 c.root-servers.net. 518400 IN A 192.33.4.12 d.root-servers.net. 518400 IN A 199.7.91.13 e.root-servers.net. 518400 IN A 192.203.230.10 f.root-servers.net. 518400 IN A 192.5.5.241 g.root-servers.net. 518400 IN A 192.112.36.4 h.root-servers.net. 518400 IN A 128.63.2.53 i.root-servers.net. 518400 IN A 192.36.148.17 j.root-servers.net. 518400 IN A 192.58.128.30 k.root-servers.net. 518400 IN A 193.0.14.129 l.root-servers.net. 518400 IN A 199.7.83.42 m.root-servers.net. 518400 IN A 202.12.27.33 a.root-servers.net. 518400 IN AAAA 2001:503:ba3e::2:30 c.root-servers.net. 518400 IN AAAA 2001:500:2::c d.root-servers.net. 518400 IN AAAA 2001:500:2d::d f.root-servers.net. 518400 IN AAAA 2001:500:2f::f h.root-servers.net. 518400 IN AAAA 2001:500:1::803f:235 i.root-servers.net. 518400 IN AAAA 2001:7fe::53 j.root-servers.net. 518400 IN AAAA 2001:503:c27::2:30 k.root-servers.net. 518400 IN AAAA 2001:7fd::1 l.root-servers.net. 518400 IN AAAA 2001:500:3::42 m.root-servers.net. 518400 IN AAAA 2001:dc3::35 ;; Query time: 58 msec ;; SERVER: 198.41.0.4#53(198.41.0.4) ;; WHEN: Wed Apr 23 14:52:37 CEST 2014 ;; MSG SIZE rcvd: 727 [root@tomshen named]#
named.localhost named.loopback 分别是本机和回环地址的区域解析库文件
[root@tomshen named]# cat named.localhost $TTL 1D @ IN SOA @ rname.invalid. ( 0 ; serial 1D ; refresh 1H ; retry 1W ; expire 3H ) ; minimum NS @ A 127.0.0.1 AAAA ::1 [root@tomshen named]# cat named.loopback $TTL 1D @ IN SOA @ rname.invalid. ( 0 ; serial 1D ; refresh 1H ; retry 1W ; expire 3H ) ; minimum NS @ A 127.0.0.1 AAAA ::1 PTR localhost. [root@tomshen named]#
/etc/named.conf为bind的主配置文件
[root@tomshen ~]# 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. // 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; }; recursion yes; dnssec-enable yes; dnssec-validation yes; dnssec-lookaside auto; /* Path to ISC DLV key */ bindkeys-file "/etc/named.iscdlv.key"; managed-keys-directory "/var/named/dynamic"; }; logging { #日志配置段 channel default_debug { file "data/named.run"; severity dynamic; }; }; zone "." IN { #区域配置段 "区域名字" type hint; file "named.ca"; #对应区域文件 }; include "/etc/named.rfc1912.zones"; #其他的区域文件的定义不在主配置文件中,在/etc/named.rfc1912.zones中,这里通过include命令将 /etc/named.rfc1912.zones包含进主配置文件中 include "/etc/named.root.key"; [root@tomshen ~]#
我们查看一下/etc/named.rfc1912.zones这个文件,可以看到其定义的区域文件
[root@tomshen ~]# cat /etc/named.rfc1912.zones // named.rfc1912.zones: // // Provided by Red Hat caching-nameserver package // // ISC BIND named zone configuration for zones recommended by // RFC 1912 section 4.1 : localhost TLDs and address zones // and http://www.ietf.org/internet-drafts/draft-ietf-dnsop-default-local-zones-02.txt // (c)2007 R W Franks // // See /usr/share/doc/bind*/sample/ for example named configuration files. // zone "localhost.localdomain" IN { type master; file "named.localhost"; allow-update { none; }; }; zone "localhost" IN { type master; file "named.localhost"; allow-update { none; }; }; zone "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa" IN { type master; file "named.loopback"; allow-update { none; }; }; zone "1.0.0.127.in-addr.arpa" IN { type master; file "named.loopback"; allow-update { none; }; }; zone "0.in-addr.arpa" IN { type master; file "named.empty"; allow-update { none; }; }; [root@tomshen ~]#
现在重启一下bind服务
[root@tomshen etc]# service named restart 停止 named:. [确定] 启动 named: [确定] [root@tomshen etc]# [root@tomshen ~]# ss -tunlp | grep :53 #查看53端口上的服务 udp UNCONN 0 0 *:53775 *:* users:(("rpc.statd",1340,8)) udp UNCONN 0 0 127.0.0.1:53 *:* users:(("named",2054,512)) udp UNCONN 0 0 ::1:53 :::* users:(("named",2054,513)) tcp LISTEN 0 3 ::1:53 :::* users:(("named",2054,21)) tcp LISTEN 0 3 127.0.0.1:53 *:* users:(("named",2054,20)) [root@tomshen ~]#
可以看到现在bind服务只有本机回环地址上监听,而由于任何服务程序如果期望其能够通过网络被其它主机访问,至少应该监听在一个能与外部主机通信的IP地址上,所以现在bind服务无法被其他主机访问。
下面我们将bind服务监听到一个能与外部主机通信的IP地址上。
[root@tomshen ~]# vim /etc/named.conf listen-on port 53 { 192.168.88.106; 192.168.88.109; 127.0.0.1; }; #将可以与外部通信的IP地址添加进去 // listen-on-v6 port 53 { ::1; }; #没有IPV6 故注释这行 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; }; recursion yes; dnssec-enable yes; dnssec-validation yes; dnssec-lookaside auto; /* Path to ISC DLV key */ bindkeys-file "/etc/named.iscdlv.key"; managed-keys-directory "/var/named/dynamic"; }; logging { channel default_debug { "/etc/named.conf" 45L, 1030C [root@tomshen ~]# service named restart #重启bind服务 停止 named:. [确定] 启动 named: [确定] [root@tomshen ~]# ss -tunlp | grep :53 udp UNCONN 0 0 *:53775 *:* users:(("rpc.statd",1340,8)) udp UNCONN 0 0 192.168.88.106:53 *:* users:(("named",2256,513)) #192.168.88.106这个能连接外部主机的IP已经监听了53端口 udp UNCONN 0 0 127.0.0.1:53 *:* users:(("named",2256,512)) tcp LISTEN 0 3 192.168.88.106:53 *:* users:(("named",2256,21)) tcp LISTEN 0 3 127.0.0.1:53 *:* users:(("named",2256,20)) [root@tomshen ~]#
现在这台主机就可以作为缓存名称服务器使用了。 现在其他主机就可以访问这台缓存名称服务器了嘛?
listen-on port 53 { 192.168.88.106; 192.168.88.109; 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; }; #注意这条设置,它限定只有本机能查询 ,我们可以将其值改为any或将这行注释掉 recursion yes; #是否允许其他主机对它做递归查询 // dnssec-enable yes; // dnssec-validation yes; // dnssec-lookaside auto; /* Path to ISC DLV key */ // bindkeys-file "/etc/named.iscdlv.key"; // managed-keys-directory "/var/named/dynamic"; }; 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";
主DNS服务器的创建需要在创建缓存DNS服务器的基础上,在配置文件定义区域然后再定义区域解析库文件即可。
[root@tomshen ~]# vim /etc/named.rfc1912.zones // named.rfc1912.zones: // // Provided by Red Hat caching-nameserver package // // ISC BIND named zone configuration for zones recommended by // RFC 1912 section 4.1 : localhost TLDs and address zones // and http://www.ietf.org/internet-drafts/draft-ietf-dnsop-default-local-zones-02.txt // (c)2007 R W Franks // // See /usr/share/doc/bind*/sample/ for example named configuration files. // zone "localhost.localdomain" IN { type master; file "named.localhost"; allow-update { none; }; }; zone "localhost" IN { type master; file "named.localhost"; allow-update { none; }; }; zone "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa" IN { type master; file "named.loopback"; allow-update { none; }; }; zone "1.0.0.127.in-addr.arpa" IN { type master; file "named.loopback"; allow-update { none; }; }; zone "0.in-addr.arpa" IN { type master; file "named.empty"; allow-update { none; }; }; zone "tomshen.icoc.cc " IN { #定义jiemengren.xyz这个区域 type master #类型为主DNS服务器 file "tomshen.icoc.cc"; #区域路径,这里为相对路径(绝对路径为/var/named/下jiemengren.xyz.zone这个文件) };
创建区域解析库文件
[root@tomshen ~]# cd /var/named [root@tomshen named]# ls data dynamic named.ca named.empty named.localhost named.loopback slaves [root@tomshen named]# vim tomshen.icoc.cc $TTL 1D @ IN SOA tomshen.icoc.cc. 768047936.qq.com ( 2016012901 1H 5M 7D 1D ) IN NS ns1.tomshen.icoc.cc. IN NS ns2.tomshen.icoc.cc. ns1 IN A 192.168.88.106 ns2 IN A 192.168.88.109 www IN A 192.168.88.106 www IN A 192.168.88.109 fatp IN CNAME www ~ ~ ~ ~ ~
使用named-checkconf 命令检查主配置文件是否有语法错误
[root@tomshen named]# named-checkconf #没有错误 [root@tomshen named]#
[root@tomshen named]# named-checkzone "tomshen.icoc.cc" /var/named/tomshen.icoc.cc.zone #检查tomshen.icoc.cc.zone是否有语法错误 zone tomshen.icoc.cc/IN: loaded serial 2016012901 OK [root@tomshen named]#
[root@tomshen named]# ps aux | grep named #查看named进程 named 5795 0.0 1.0 159520 11064 ? Ssl 20:30 0:00 /usr/sbin/named -u named #named用户创建 root 5995 0.0 0.0 103256 844 pts/0 S+ 20:58 0:00 grep named [root@tomshen named]# [root@tomshen named]# ll /etc/named.conf -l -rw-r-----. 1 root named 1060 1月 29 20:34 /etc/named.conf #主配置文件属组为named [root@tomshen named]# ll 总用量 32 drwxrwx---. 2 named named 4096 1月 24 15:51 data drwxrwx---. 2 named named 4096 1月 29 20:27 dynamic -rw-r-----. 1 root named 2075 4月 23 2014 named.ca #可以看到其他区域解析库文件属组为named,且其他用户没有任何访问权限 -rw-r-----. 1 root named 152 12月 15 2009 named.empty -rw-r-----. 1 root named 152 6月 21 2007 named.localhost -rw-r-----. 1 root named 168 12月 15 2009 named.loopback drwxrwx---. 2 named named 4096 7月 24 2015 slaves -rw-r-----. 1 root named 293 1月 29 20:55 tomshen.icoc.cc.zone [root@tomshen named]# [root@tomshen named]# chmod 640 tomshen.icoc.cc.zone #使其他用户没有任何访问权限 [root@tomshen named]# chown :named tomshen.icoc.cc.zone #使其属组为named [root@tomshen named]# ll 总用量 32 drwxrwx---. 2 named named 4096 1月 24 15:51 data drwxrwx---. 2 named named 4096 1月 29 20:27 dynamic -rw-r-----. 1 root named 2075 4月 23 2014 named.ca -rw-r-----. 1 root named 152 12月 15 2009 named.empty -rw-r-----. 1 root named 152 6月 21 2007 named.localhost -rw-r-----. 1 root named 168 12月 15 2009 named.loopback drwxrwx---. 2 named named 4096 7月 24 2015 slaves -rw-r-----. 1 root named 293 1月 29 20:55 tomshen.icoc.cc.zone [root@tomshen named]#
安装bind程序
编辑从DNS的named.conf文件
[root@tomshen ~]# vim /etc/named.conf options { listen-on port 53 { 192.179.100.1; 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; }; recursion yes; // dnssec-enable yes; // dnssec-validation yes; // dnssec-lookaside auto; /* Path to ISC DLV key */ // bindkeys-file "/etc/named.iscdlv.key"; managed-keys-directory "/var/named/dynamic"; }; // // 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. //
修改主DNS的/etc/named.rfc1912.zones文件。
[root@tomshen ~]# vim /etc/named.rfc1912.zones zone "tomshen.icoc.cc " IN { type master; file "tomshen.icoc.cc"; allow-transfer { 192.179.100.1; }; # 在这添加从DNS的IP };
修改主DNS的区域解析库文件tomshen.icoc.cc.zone
$TTL 1D @ IN SOA ns1.jiemengren.xyz. 768047936.qq.com ( 2016012901 1H 5M 7D 1D ) IN NS ns1.tomshen.icoc.cc. IN NS ns2.tomshen.icoc.cc. IN NS slavedns.tomshen.icoc.cc. #添加指向从DNS的NS ns1 IN A 192.168.88.106 ns2 IN A 192.168.88.109 www IN A 192.168.88.106 www IN A 192.168.88.109 slavedns.tomshen.icoc.cc. IN A 192.179.100.1 #添加指向从DNS的A ftp IN CNAME www
设置从DNS的/etc/named.rfc1912.zones 添加以下内容
zone "tomshen.icoc.cc" IN { type slave; file "slaves/tomshen.icoc.cc.zone"; #设置从DNS区域解析库文件存放的目录/var/named/slaves/tomshen.icoc.cc.zone masters { 192.168.88.106; }; #指明主DNS是谁