优秀的DEMO

cat /etc/init.d/functions   -->里面有颜色定义
cat /etc/rc.d/rc.sysinit
cat /etc/init.d/nfs
cat /etc/init.d/portmap
cat /etc/init.d/httpd

0. function文件

 # -*-Shell-script-*-
#
# functions This file contains functions to be used by most or all
# shell scripts in the /etc/init.d directory.
# TEXTDOMAIN=initscripts # Make sure umask is sane
umask # Set up a default search path.
PATH="/sbin:/usr/sbin:/bin:/usr/bin"
export PATH # Get a sane screen width
[ -z "${COLUMNS:-}" ] && COLUMNS= [ -z "${CONSOLETYPE:-}" ] && CONSOLETYPE="$(/sbin/consoletype)" if [ -f /etc/sysconfig/i18n -a -z "${NOLOCALE:-}" -a -z "${LANGSH_SOURCED:-}" ] ; then
. /etc/profile.d/lang.sh >/dev/null
# avoid propagating LANGSH_SOURCED any further
unset LANGSH_SOURCED
fi # Read in our configuration
if [ -z "${BOOTUP:-}" ]; then
if [ -f /etc/sysconfig/init ]; then
. /etc/sysconfig/init
else
# This all seem confusing? Look in /etc/sysconfig/init,
# or in /usr/doc/initscripts-*/sysconfig.txt
BOOTUP=color
RES_COL=
MOVE_TO_COL="echo -en \\033[${RES_COL}G"
SETCOLOR_SUCCESS="echo -en \\033[1;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_WARNING="echo -en \\033[1;33m"
SETCOLOR_NORMAL="echo -en \\033[0;39m"
LOGLEVEL=
fi
if [ "$CONSOLETYPE" = "serial" ]; then
BOOTUP=serial
MOVE_TO_COL=
SETCOLOR_SUCCESS=
SETCOLOR_FAILURE=
SETCOLOR_WARNING=
SETCOLOR_NORMAL=
fi
fi # Interpret escape sequences in an fstab entry
fstab_decode_str() {
fstab-decode echo "$1"
} # Check if any of $pid (could be plural) are running
checkpid() {
local i for i in $* ; do
[ -d "/proc/$i" ] && return
done
return
} __readlink() {
ls -bl "$@" >/dev/null| awk '{ print $NF }'
} __fgrep() {
s=$
f=$
while read line; do
if strstr "$line" "$s"; then
echo $line
return
fi
done < $f
return
} # __umount_loop awk_program fstab_file first_msg retry_msg retry_umount_args
# awk_program should process fstab_file and return a list of fstab-encoded
# paths; it doesn't have to handle comments in fstab_file.
__umount_loop() {
local remaining sig=
local retry= count remaining=$(LC_ALL=C awk "/^#/ {next} $1" "$2" | sort -r)
while [ -n "$remaining" -a "$retry" -gt ]; do
if [ "$retry" -eq ]; then
action "$3" fstab-decode umount $remaining
else
action "$4" fstab-decode umount $ $remaining
fi
count=
remaining=$(LC_ALL=C awk "/^#/ {next} $1" "$2" | sort -r)
while [ "$count" -gt ]; do
[ -z "$remaining" ] && break
count=$(($count-))
usleep
remaining=$(LC_ALL=C awk "/^#/ {next} $1" "$2" | sort -r)
done
[ -z "$remaining" ] && break
fstab-decode /sbin/fuser -m $remaining >/dev/null | sed -e "s/\b$$\b//" | xargs kill $sig >/dev/null
sleep
retry=$(($retry -))
sig=-
done
} # Similar to __umount loop above, specialized for loopback devices
__umount_loopback_loop() {
local remaining devremaining sig=
local retry= remaining=$(awk '$1 ~ /^\/dev\/loop/ && $2 != "/" {print $2}' /proc/mounts)
devremaining=$(awk '$1 ~ /^\/dev\/loop/ && $2 != "/" {print $1}' /proc/mounts)
while [ -n "$remaining" -a "$retry" -gt ]; do
if [ "$retry" -eq ]; then
action $"Unmounting loopback filesystems: " \
fstab-decode umount $remaining
else
action $"Unmounting loopback filesystems (retry):" \
fstab-decode umount $remaining
fi
for dev in $devremaining ; do
losetup $dev > /dev/null >& && \
action $"Detaching loopback device $dev: " \
losetup -d $dev
done
remaining=$(awk '$1 ~ /^\/dev\/loop/ && $2 != "/" {print $2}' /proc/mounts)
devremaining=$(awk '$1 ~ /^\/dev\/loop/ && $2 != "/" {print $1}' /proc/mounts)
[ -z "$remaining" ] && break
fstab-decode /sbin/fuser -k -m $sig $remaining >/dev/null
sleep
retry=$(($retry -))
sig=-
done
} # __proc_pids {program} [pidfile]
# Set $pid to pids from /var/run* for {program}. $pid should be declared
# local in the caller.
# Returns LSB exit code for the 'status' action.
__pids_var_run() {
local base=${##*/}
local pid_file=${:-/var/run/$base.pid} pid=
if [ -f "$pid_file" ] ; then
local line p [ ! -r "$pid_file" ] && return # "user had insufficient privilege"
while : ; do
read line
[ -z "$line" ] && break
for p in $line ; do
[ -z "${p//[0-9]/}" -a -d "/proc/$p" ] && pid="$pid $p"
done
done < "$pid_file" if [ -n "$pid" ]; then
return
fi
return # "Program is dead and /var/run pid file exists"
fi
return # "Program is not running"
} # Output PIDs of matching processes, found using pidof
__pids_pidof() {
pidof -c -o $$ -o $PPID -o %PPID -x "$1" || \
pidof -c -o $$ -o $PPID -o %PPID -x "${1##*/}"
} # A function to start a program.
daemon() {
# Test syntax.
local gotbase= force= nicelevel corelimit
local pid base= user= nice= bg= pid_file=
local cgroup=
nicelevel=
while [ "$1" != "${1##[-+]}" ]; do
case $ in
'') echo $"$0: Usage: daemon [+/-nicelevel] {program}"
return ;;
--check)
base=$
gotbase="yes"
shift
;;
--check=?*)
base=${#--check=}
gotbase="yes"
shift
;;
--user)
user=$
shift
;;
--user=?*)
user=${#--user=}
shift
;;
--pidfile)
pid_file=$
shift
;;
--pidfile=?*)
pid_file=${#--pidfile=}
shift
;;
--force)
force="force"
shift
;;
[-+][-]*)
nice="nice -n $1"
shift
;;
*) echo $"$0: Usage: daemon [+/-nicelevel] {program}"
return ;;
esac
done # Save basename.
[ -z "$gotbase" ] && base=${##*/} # See if it's already running. Look *only* at the pid file.
__pids_var_run "$base" "$pid_file" [ -n "$pid" -a -z "$force" ] && return # make sure it doesn't core dump anywhere unless requested
corelimit="ulimit -S -c ${DAEMON_COREFILE_LIMIT:-0}" # if they set NICELEVEL in /etc/sysconfig/foo, honor it
[ -n "${NICELEVEL:-}" ] && nice="nice -n $NICELEVEL" # if they set CGROUP_DAEMON in /etc/sysconfig/foo, honor it
if [ -n "${CGROUP_DAEMON}" ]; then
if [ ! -x /bin/cgexec ]; then
echo -n "Cgroups not installed"; warning
echo
else
cgroup="/bin/cgexec";
for i in $CGROUP_DAEMON; do
cgroup="$cgroup -g $i";
done
fi
fi # Echo daemon
[ "${BOOTUP:-}" = "verbose" -a -z "${LSB:-}" ] && echo -n " $base" # And start it up.
if [ -z "$user" ]; then
$cgroup $nice /bin/bash -c "$corelimit >/dev/null 2>&1 ; $*"
else
$cgroup $nice runuser -s /bin/bash $user -c "$corelimit >/dev/null 2>&1 ; $*"
fi [ "$?" -eq ] && success $"$base startup" || failure $"$base startup"
} # A function to stop a program.
killproc() {
local RC killlevel= base pid pid_file= delay RC=; delay=
# Test syntax.
if [ "$#" -eq ]; then
echo $"Usage: killproc [-p pidfile] [ -d delay] {program} [-signal]"
return
fi
if [ "$1" = "-p" ]; then
pid_file=$
shift
fi
if [ "$1" = "-d" ]; then
delay=$
shift
fi # check for second arg to be kill level
[ -n "${2:-}" ] && killlevel=$ # Save basename.
base=${##*/} # Find pid.
__pids_var_run "$1" "$pid_file"
RC=$?
if [ -z "$pid" ]; then
if [ -z "$pid_file" ]; then
pid="$(__pids_pidof "$")"
else
[ "$RC" = "" ] && { failure $"$base shutdown" ; return $RC ;}
fi
fi # Kill it.
if [ -n "$pid" ] ; then
[ "$BOOTUP" = "verbose" -a -z "${LSB:-}" ] && echo -n "$base "
if [ -z "$killlevel" ] ; then
if checkpid $pid >&; then
# TERM first, then KILL if not dead
kill -TERM $pid >/dev/null >&
usleep
if checkpid $pid && sleep &&
checkpid $pid && sleep $delay &&
checkpid $pid ; then
kill -KILL $pid >/dev/null >&
usleep
fi
fi
checkpid $pid
RC=$?
[ "$RC" -eq ] && failure $"$base shutdown" || success $"$base shutdown"
RC=$((! $RC))
# use specified level only
else
if checkpid $pid; then
kill $killlevel $pid >/dev/null >&
RC=$?
[ "$RC" -eq ] && success $"$base $killlevel" || failure $"$base $killlevel"
elif [ -n "${LSB:-}" ]; then
RC= # Program is not running
fi
fi
else
if [ -n "${LSB:-}" -a -n "$killlevel" ]; then
RC= # Program is not running
else
failure $"$base shutdown"
RC=
fi
fi # Remove pid file if any.
if [ -z "$killlevel" ]; then
rm -f "${pid_file:-/var/run/$base.pid}"
fi
return $RC
} # A function to find the pid of a program. Looks *only* at the pidfile
pidfileofproc() {
local pid # Test syntax.
if [ "$#" = ] ; then
echo $"Usage: pidfileofproc {program}"
return
fi __pids_var_run "$1"
[ -n "$pid" ] && echo $pid
return
} # A function to find the pid of a program.
pidofproc() {
local RC pid pid_file= # Test syntax.
if [ "$#" = ]; then
echo $"Usage: pidofproc [-p pidfile] {program}"
return
fi
if [ "$1" = "-p" ]; then
pid_file=$
shift
fi
fail_code= # "Program is not running" # First try "/var/run/*.pid" files
__pids_var_run "$1" "$pid_file"
RC=$?
if [ -n "$pid" ]; then
echo $pid
return
fi [ -n "$pid_file" ] && return $RC
__pids_pidof "$1" || return $RC
} status() {
local base pid lock_file= pid_file= # Test syntax.
if [ "$#" = ] ; then
echo $"Usage: status [-p pidfile] {program}"
return
fi
if [ "$1" = "-p" ]; then
pid_file=$
shift
fi
if [ "$1" = "-l" ]; then
lock_file=$
shift
fi
base=${##*/} # First try "pidof"
__pids_var_run "$1" "$pid_file"
RC=$?
if [ -z "$pid_file" -a -z "$pid" ]; then
pid="$(__pids_pidof "$")"
fi
if [ -n "$pid" ]; then
echo $"${base} (pid $pid) is running..."
return
fi case "$RC" in
)
echo $"${base} (pid $pid) is running..."
return
;;
)
echo $"${base} dead but pid file exists"
return
;;
)
echo $"${base} status unknown due to insufficient privileges."
return
;;
esac
if [ -z "${lock_file}" ]; then
lock_file=${base}
fi
# See if /var/lock/subsys/${lock_file} exists
if [ -f /var/lock/subsys/${lock_file} ]; then
echo $"${base} dead but subsys locked"
return
fi
echo $"${base} is stopped"
return
} echo_success() {
[ "$BOOTUP" = "color" ] && $MOVE_TO_COL
echo -n "["
[ "$BOOTUP" = "color" ] && $SETCOLOR_SUCCESS
echo -n $" OK "
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo -n "]"
echo -ne "\r"
return
} echo_failure() {
[ "$BOOTUP" = "color" ] && $MOVE_TO_COL
echo -n "["
[ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
echo -n $"FAILED"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo -n "]"
echo -ne "\r"
return
} echo_passed() {
[ "$BOOTUP" = "color" ] && $MOVE_TO_COL
echo -n "["
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo -n $"PASSED"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo -n "]"
echo -ne "\r"
return
} echo_warning() {
[ "$BOOTUP" = "color" ] && $MOVE_TO_COL
echo -n "["
[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo -n $"WARNING"
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
echo -n "]"
echo -ne "\r"
return
} # Inform the graphical boot of our current state
update_boot_stage() {
if [ -x /bin/plymouth ]; then
/bin/plymouth --update="$1"
fi
return
} # Log that something succeeded
success() {
[ "$BOOTUP" != "verbose" -a -z "${LSB:-}" ] && echo_success
return
} # Log that something failed
failure() {
local rc=$?
[ "$BOOTUP" != "verbose" -a -z "${LSB:-}" ] && echo_failure
[ -x /bin/plymouth ] && /bin/plymouth --details
return $rc
} # Log that something passed, but may have had errors. Useful for fsck
passed() {
local rc=$?
[ "$BOOTUP" != "verbose" -a -z "${LSB:-}" ] && echo_passed
return $rc
} # Log a warning
warning() {
local rc=$?
[ "$BOOTUP" != "verbose" -a -z "${LSB:-}" ] && echo_warning
return $rc
} # Run some action. Log its output.
action() {
local STRING rc STRING=$
echo -n "$STRING "
shift
"$@" && success $"$STRING" || failure $"$STRING"
rc=$?
echo
return $rc
} # returns OK if $ contains $
strstr() {
[ "${1#*$2*}" = "$1" ] && return
return
} # Confirm whether we really want to run this service
confirm() {
[ -x /bin/plymouth ] && /bin/plymouth --hide-splash
while : ; do
echo -n $"Start service $1 (Y)es/(N)o/(C)ontinue? [Y] "
read answer
if strstr $"yY" "$answer" || [ "$answer" = "" ] ; then
return
elif strstr $"cC" "$answer" ; then
rm -f /var/run/confirm
[ -x /bin/plymouth ] && /bin/plymouth --show-splash
return
elif strstr $"nN" "$answer" ; then
return
fi
done
} # resolve a device node to its major:minor numbers in decimal or hex
get_numeric_dev() {
(
fmt="%d:%d"
if [ "$1" == "hex" ]; then
fmt="%x:%x"
fi
ls -lH "$2" | awk '{ sub(/,/, "", $5); printf("'"$fmt"'", $5, $6); }'
) >/dev/null
} # Check whether file $ is a backup or rpm-generated file and should be ignored
is_ignored_file() {
case "$1" in
*~ | *.bak | *.orig | *.rpmnew | *.rpmorig | *.rpmsave)
return
;;
esac
return
} # Evaluate shvar-style booleans
is_true() {
case "$1" in
[tT] | [yY] | [yY][eE][sS] | [tT][rR][uU][eE])
return
;;
esac
return
} # Evaluate shvar-style booleans
is_false() {
case "$1" in
[fF] | [nN] | [nN][oO] | [fF][aA][lL][sS][eE])
return
;;
esac
return
} # Apply sysctl settings, including files in /etc/sysctl.d
apply_sysctl() {
sysctl -e -p /etc/sysctl.conf >/dev/null >&
for file in /etc/sysctl.d/* ; do
is_ignored_file "$file" && continue
test -f "$file" && sysctl -e -p "$file" >/dev/null 2>&1
done
} key_is_random() {
[ "$1" = "/dev/urandom" -o "$1" = "/dev/hw_random" \
-o "$1" = "/dev/random" ]
} find_crypto_mount_point() {
local fs_spec fs_file fs_vfstype remaining_fields
local fs
while read fs_spec fs_file remaining_fields; do
if [ "$fs_spec" = "/dev/mapper/$1" ]; then
echo $fs_file
break;
fi
done < /etc/fstab
} # Because of a chicken/egg problem, init_crypto must be run twice. /var may be
# encrypted but /var/lib/random-seed is needed to initialize swap.
init_crypto() {
local have_random dst src key opt mode owner params makeswap skip arg opt
local param value rc ret mke2fs mdir prompt mount_point ret=0
have_random=$1
while read dst src key opt; do
[ -z "$dst" -o "${dst#\#}" != "$dst" ] && continue
[ -b "/dev/mapper/$dst" ] && continue;
if [ "$have_random" = 0 ] && key_is_random "$key"; then
continue
fi
if [ -n "$key" -a "x$key" != "xnone" ]; then
if test -e "$key" ; then
owner=$(ls -l $key | (read a b owner rest; echo $owner))
if ! key_is_random "$key"; then
mode=$(ls -l "$key" | cut -c 5-10)
if [ "$mode" != "------" ]; then
echo $"INSECURE MODE FOR $key"
fi
fi
if [ "$owner" != root ]; then
echo $"INSECURE OWNER FOR $key"
fi
else
echo $"Key file for $dst not found, skipping"
ret=1
continue
fi
else
key=""
fi
params=""
makeswap=""
mke2fs=""
skip=""
# Parse the src field for UUID= and convert to real device names
if [ "${src%%=*}" == "UUID" ]; then
src=$(/sbin/blkid -t "$src" -l -o device)
elif [ "${src/^\/dev\/disk\/by-uuid\/}" != "$src" ]; then
src=$(__readlink $src)
fi
# Is it a block device?
[ -b "$src" ] || continue
# Is it already a device mapper slave? (this is gross)
devesc=${src##/dev/}
devesc=${devesc//\//!}
for d in /sys/block/dm-*/slaves ; do
[ -e $d/$devesc ] && continue
done
# Parse the options field, convert to cryptsetup parameters and
# contruct the command line
while [ -n "$opt" ]; do
arg=${opt%%,*}
opt=${opt##$arg}
opt=${opt##,}
param=${arg%%=*}
value=${arg##$param=} case "$param" in
cipher)
params="$params -c $value"
if [ -z "$value" ]; then
echo $"$dst: no value for cipher option, skipping"
skip="yes"
fi
;;
size)
params="$params -s $value"
if [ -z "$value" ]; then
echo $"$dst: no value for size option, skipping"
skip="yes"
fi
;;
hash)
params="$params -h $value"
if [ -z "$value" ]; then
echo $"$dst: no value for hash option, skipping"
skip="yes"
fi
;;
verify)
params="$params -y"
;;
swap)
makeswap=yes
;;
tmp)
mke2fs=yes
esac
done
if [ "$skip" = "yes" ]; then
ret=
continue
fi
if [ -z "$makeswap" ] && cryptsetup isLuks "$src" >/dev/null ; then
if key_is_random "$key"; then
echo $"$dst: LUKS requires non-random key, skipping"
ret=
continue
fi
if [ -n "$params" ]; then
echo "$dst: options are invalid for LUKS partitions," \
"ignoring them"
fi
if [ -n "$key" ]; then
/sbin/cryptsetup -d $key luksOpen "$src" "$dst" <& >/dev/null && success || failure
rc=$?
else
mount_point="$(find_crypto_mount_point $dst)"
[ -n "$mount_point" ] || mount_point=${src##*/}
prompt=$(printf $"%s is password protected" "$mount_point")
plymouth ask-for-password --prompt "$prompt" --command="/sbin/cryptsetup luksOpen -T1 $src $dst" <&
rc=$?
fi
else
[ -z "$key" ] && plymouth --hide-splash
/sbin/cryptsetup $params ${key:+-d $key} create "$dst" "$src" <& >/dev/null && success || failure
rc=$?
[ -z "$key" ] && plymouth --show-splash
fi
if [ $rc -ne ]; then
ret=
continue
fi
if [ -b "/dev/mapper/$dst" ]; then
if [ "$makeswap" = "yes" ]; then
mkswap "/dev/mapper/$dst" >/dev/null >/dev/null
fi
if [ "$mke2fs" = "yes" ]; then
if mke2fs "/dev/mapper/$dst" >/dev/null >/dev/null \
&& mdir=$(mktemp -d /tmp/mountXXXXXX); then
mount "/dev/mapper/$dst" "$mdir" && chmod "$mdir"
umount "$mdir"
rmdir "$mdir"
fi
fi
fi
done < /etc/crypttab
return $ret
} # A sed expression to filter out the files that is_ignored_file recognizes
__sed_discard_ignored_files='/\(~\|\.bak\|\.orig\|\.rpmnew\|\.rpmorig\|\.rpmsave\)$/d'

1. portmap脚本

 #! /bin/sh
#
# portmap Start/Stop RPC portmapper
#
# chkconfig:
# description: The portmapper manages RPC connections, which are used by \
# protocols such as NFS and NIS. The portmap server must be \
# running on machines which act as servers for protocols which \
# make use of the RPC mechanism.
# processname: portmap # This is an interactive program, we need the current locale
[ -f /etc/profile.d/lang.sh ] && . /etc/profile.d/lang.sh
# We can't Japanese on normal console at boot time, so force LANG=C.
if [ "$LANG" = "ja" -o "$LANG" = "ja_JP.eucJP" ]; then
if [ "$TERM" = "linux" ] ; then
LANG=C
fi
fi # Source function library.
. /etc/init.d/functions # Get config.
if [ -f /etc/sysconfig/network ]; then
. /etc/sysconfig/network
else
echo $"Networking not configured - exiting"
...skipping...
stop
start
pmap_set < /var/run/portmap.state
rm -f /var/run/portmap.state
} # See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status portmap
;;
restart|reload)
restart
;;
condrestart)
[ -f /var/lock/subsys/portmap ] && restart || :
;;
*)
echo $"Usage: $0 {start|stop|status|restart|reload|condrestart}"
exit
esac

2. rc.sysinit

 #!/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
fi if [ ! -e /proc/mounts ]; then
mount -n -t proc /proc /proc
mount -n -t sysfs /sys /sys >/dev/null >&
fi
if [ ! -d /proc/bus/usb ]; then
modprobe usbcore >/dev/null >& && 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 #
mount -n -o remount /dev/shm >/dev/null >& . /etc/init.d/functions PLYMOUTH=
[ -x /bin/plymouth ] && PLYMOUTH=yes # Check SELinux status
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=
fi
fi if [ -n "$SELINUX_STATE" -a -x /sbin/restorecon ] && __fgrep " /dev " /proc/mounts >/dev/null >& ; then
/sbin/restorecon -R -F /dev >/dev/null
fi disable_selinux() {
echo $"*** Warning -- SELinux is active"
echo $"*** Disabling security enforcement for system recovery."
echo $"*** Run 'setenforce 1' to reenable."
echo "" > "/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 "" > /selinux/enforce
[ -n "$PLYMOUTH" ] && plymouth --hide-splash if [ "$AUTORELABEL" = "" ]; 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 >&
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
if [ -f /proc/sys/kernel/modprobe ]; then
if ! strstr "$cmdline" nomodules && [ -f /proc/modules ] ; then
sysctl -w kernel.modprobe="/sbin/modprobe" >/dev/null >&
else
# We used to set this to NULL, but that causes 'failed to exec' messages"
sysctl -w kernel.modprobe="/bin/true" >/dev/null >&
fi
fi touch /dev/.in_sysinit >/dev/null >& # 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=}
fi
done
fi
fi nashpid=$(pidof nash >/dev/null)
[ -n "$nashpid" ] && kill $nashpid >/dev/null >&
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
action $"Setting up Logical Volume Management:" /sbin/lvm vgchange -a ay --sysinit
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

FLT的DEMO

0. 一键式[未完成版本]

 #set env
export PATH=$PATH:/bin:/sbin:/usr/sbin
export LANG='us' #Root allowed
if [ `whoami` != 'root' ];then
echo "Please run this script with root "
exit
fi #define cmd var
SERVICE=`which service`
CHKCONFIG= `which chkconfig` #import libiary
. /etc/init.d/functions #Config Yum Config
function yum(){
echo "Config Yum Centos-Base.repo"
cd /etc/yum.repos.d/
cp rhel-source.repo rhel-source.repo.$(date +%F)
ping www.baidu.com
[ $? -eq ] && echo $"Networking not configured" && exit
wget --quiet http://mirrors.163.com/.help/CentOS6-Base-163.repo
sed -i 's/$releasever/6/g' CentOS6-Base-.repo
chmod CentOS6-Base-.repo
chown root.root CentOS6-Base-.repo
} #Install Init Package
function installTool(){
echo "sysstat ntp net-snmp lrzsz rsync"
yum install sysstat ntp net-snmp lrzsz rsync >&/dev/null
} #Chinese GB18030
function initI18n(){
echo "#set LANG="zh_cn.gb18030""
cp /etc/sysconfig/i18n /etc/sysconfig/i18n_`date +%F`
sed -i 's/LANG="en_US.UTF-8"/LANG="zh_CN.GB18030"/g' /etc/sysconfig/i18n
grep LANG /etc/sysconfig/i18n
sleep
} #close selinux and iptables
initFirewall(){
echo "#close selinux and firewall"
cp /etc/selinux/config /etc/selinux/config_`date +%F`
/etc/init.d/iptables stop
sed -i 's/SELINUX=enable/SELINUX=disable/g' /etc/selinux/config
setenforce
/etc/init.d/iptables status
grep SELINUX=disable /etc/selinux/config
echo "Close selinux Ok "
echo "Close firewall Ok "
sleep
} #Init Auto Startup Service
function initService(){
echo "Close Nonuseful service..."
exprt LANG=us
chkconfig |grep :on | awk '{print $1}' | grep -Ev "sshd|network|crond|sysstat|rsyslog" | xargs -I{} chkconfig {} off
echo "Service sshd|network|crond|sysstat|rsyslog is Running...."
sleep
} #Init ssh
function ssh(){
echo "config sshConfig ...."
cp /etc/ssh/sshd_config /etc/ssh/sshd_config_`date +%F`
sed -i 's#GSSAPIAuthentication yes#GSSAPIAuthentication no#g' /etc/ssh/sshd_config
sed -i 's#PermitRootLogin no#PermitRootLogin no#g' /etc/ssh/sshd_config
sed -i 's%#Port 22%Port 11544%g' /etc/ssh/sshd_config
} #AddUser
function addUser(){
echo "add User for Linux System..."
cp /etc/sudoers /etc/sudoers_`date +%F`
saUserArr={omc webserver webserverpt}
groupadd -g sa
for((i=;i<${#saUserArr[@]};i++))
do
useradd -g sa -u88${i} ${saUserArr[$i]}
echo "${saUserArr[$i]}123"|passwd ${saUserArr[$i]} --stdin
# add sudoers
# ...
# /usr/sbin/visudo -c
# [ $? -ne ] && /bin/cp /etc/sudoers.`date +%F` /etc/sudoers && echo $"Sudoers not configured --exit" && exit
# action $"useradd is ok " /bin/true
done
} #Sync Time
function sysncTime(){
if [ `grep pool.ntp.ort /var/spool/cron/root|grep -v grep |wc -l` -lt ];then
echo "*/5 * * * * /usr/sbin/ntpdate cn.pool.ntp.org 2&>/dev/null" >> /var/spool/cron/root
fi
} #adjuct File
function openFile(){
echo "adjust the max opened files are 65535"
cp /etc/security/limits.conf /etc/security/limits.conf_`date +%F`
echo ' * - nofile 65535' >> /etc/security/limits.conf
ulimit -SHn
echo "adjust the max opened files are 65535 is ok "
sleep
} #adjust kernal
function optimizationKernal(){
echo "optimizationKernal..."
cp /etc/sysctl.conf /etc/sysctl.conf_`date +%F`
cat >> /etc/sysctl.conf<<EOF
net.ipv4.tcp_timestamps=
EOF
/sbin/sysctl -p && action "optimizationKernal is ok " /bin/true || actio "optimizationKernal is wrong" /bin/false } function safe(){
echo ""
}

1. 清除日志 

 #!/bin/sh
#clear log file
LOG_DIR=/var/log
ROOT_UID=
#ROOT用户执行
if [ "$UID" -ne ROOT_UID ]
then
echo 'Must be root to run this script'
exit
fi
cd $LOG_DIR ||{
echo "Cannot change to $LOG_DIR " >/dev/null
exit
}
cat /dev/null > messages
echo "Logs cleaned up"
exit

2. 利用shell数组函数检查多个url地址的案例

#!/bin/sh
#use array by #use function
. /etc/init.d/functions array=(
www.baidu.com
www.hao123.com
www.51cto.com
) function wait(){
echo -n "3mins to start the script..."
for((i=;i<${#array[*]};i++))
do
echo -n '.';
sleep
done
} function check_url(){
for ((i=;i<${#array[*]};i++))
do
judge=(`curl -I ${array[$i]} -s |head -`)
#echo "${array[$i]} ------------> ${judge[2]}"
if [ "${judge[1]}"=="" ] && [ "${judge[2]}"=="OK" ];then
action "${array[$i]} ------------> ${judge[2]}" /bin/true
else
action "${array[$i]} ------------> ${judge[2]}" /bin/false
fi
done
}
wait
echo -e "\n"
check_url

3. 数组的学习

 #!/bin/sh
#use array by
array=(
hello
world I
hava
a
dream)
arr=(`ls /home/omc/*.sh`)
echo "---------------Array---------------------"
for ((i=0;i<=${#array[*]};i++))
do
echo "this is $i-------------------->${array[$i]}"
done
echo "------------------------------------"
echo "total : ${#array[*]}"
echo "---------------Ls *.sh--------------------"
for((i=0;i<${#arr[*]};i++))
do
echo "this is $i -------------------> ${arr[$i]}"
done
echo "------------------------------------"
echo "total : ${#arr[*]}"

4. 监控WEB的URL

 [root@lnmp01 scripts]# cat check_web.sh
#!/bin/sh
########################################################
RETVAL=
SCRIPT_PATH="/root/scripts"
MAIL_GROUP="623799533@qq.com 623799531@qq.com"
LOG_FILE="/tmp/web_check.log"
FAIL_COUNT=
function getUrlState(){
for (( i = ; i < ; i++ )); do
wget -T --tries= --spider http://${URL} &>/dev/null
[ $? -ne ] && let ${FAIL_COUNT}+=
done if [ ${FAIL_COUNT} -gt ];then
RETVAL=
NowTime=`date +%m-%d %H:%M:%S`
TITLE="http://${URL} sevice is error,${NowTime}"
echo "send to :${MAIL_USER},Title :${TITLE}" >>${LOG_FILE}
for MAIL_USER in `$MAIL_GROUP`
do
mail -s ${TITLE} ${MAIL_USER} <${LOG_FILE}
done
else
RETVAL=
fi
return "$RETVAL"
} [ ! -d "$SCRIPT_PATH" ] && {
mkdir -p "$SCRIPT_PATH"
} [ ! -f "$SCRIPT_PATH/domain.list" ] && {
cat > "$SCRIPT_PATH/domain.list" << EOF
www.baidu.com
www.51cto.com
www.http:www.hao123.com
EOF
} for URL in `cat $SCRIPT_PATH/domain.list`
do
echo -n "checking $URL..."
getUrlState $URL && echo OK || echo no
done
[root@lnmp01 scripts]#

5. for循环的使用

 方案一:计算某个access_log文件的访问总次数:
#!/bin/sh
num=`awk '{print $8}' $ |grep -v eth0|awk -F '.' '{print $4}'`
sum=
for line in $num
do
[ -n $line ] || continue
((sum+=$line))
done
echo "Num is $sum" 问题二:打印文件夹
ls -F|grep / 问题三:打印文件夹
#!/bin/sh
openvpn=""
openvpn_locations="/usr/bin/openvpn /usr/local/sbin/openvpn"
for location in $openvpn_locations
do
[ -f $location ] && openvpn=$location
done 问题四:打印9* #!/bin/sh
for a in `seq `
do
for b in `seq `
do
if [ $a -ge $b ];then
echo -en "$a * $b = $(expr $a \* $b)"
fi
done
echo " "
done 问题5:编写连续IP的添加
#!/bin/sh print_usage(){
echo "USAGE: $0 {up/down}"
exit
} [ $# -ne ] && print_usage ip_conf(){
for((i=;i<=;i++))
do
if [ $i -ne ];then
ifconfig eth0:$i 192.168..$i netmask 255.255.255.0 $
else
continue
fi
done
} case $ in
up)
ip_conf;;
down)
ip_conf;;
*)
echo "something wrong..."
esac

6. while循环的使用

 ------------------------------------------------------------------------------------------
方案一:
#!/bin/sh
#cal + + +...+
i=
while ((i>))
do
echo $i
((i--))
done
------------------------------------------------------------------------------------------
方案二:
#!/bin/sh
#cal + + +...+
i=
while [[ $i > ]]
do
echo $i
((i--))
done ------------------------------------------------------------------------------------------
方案三:
#!/bin/sh
#cal + + +...+
i=
while ((i--))
do
echo $i
done ------------------------------------------------------------------------------------------
方案四:
#!/bin/sh
#cal + + +...+
i=
while [ $i -gt ]
do
echo $i
((i--))
done

7. 计算1+2+3+...+100

 方案1:for循环结构及(())计算式shell脚本
#!/bin/sh
#cal + + +...+
j=
for ((i=;i<=;i++))
do
((j+=i))
done echo "1 + 2 + 3 +...+100="$j ---------------------------------------------------------------------------------------
方案二:使用seq命令加for循环语法及let命令计算式脚本
#!/bin/sh
#cal + + +...+
sum=
for i in `seq `
do
let sum+=i;
done
echo "1 + 2 + 3 +...+100="$sum ---------------------------------------------------------------------------------------
方案三:seq、tr、sed、bc联手完成计算的方法
seq | tr '\n' '+'|sed 's#\+$#\n#g'|bc ==>拼接的字符串表达式结尾加号替换为换行(回车)符。
---------------------------------------------------------------------------------------
方案四:
#!/bin/sh
i=
while ((i <= ))
do
((j=j+i))
((i++))
done
echo $j ---------------------------------------------------------------------------------------
方案五:
seq |awk '{total+=$1} END {print total}'

8. case语句联系

 案例一: 纯case联系
#!/bin/sh
read -p "Please input the number of two:" num
case $num in
"" )
echo "the number you put is 1" ;;
"")
echo "the number you put is 2";;
[-])
echo "the number you put is $num";;
*)
echo "something must be wrong ...";
esac 案例二:case-if联系
#!/bin/sh
read -p "Please input the number of two:" num
if [ $num -eq ];then
echo ""
elif [ $num -eq ];then
echo ""
elif [ $num -eq ];then
echo ""
else
echo "$num"
fi 案例三:
#/bin/sh
read -p "Please input the number of two:" fruit
case "$fruit" in
apple|APPLE)
echo -e "Apple";;

8.1 if语句

 #!/bin/sh
#Author: ftl
#Date: print_usage(){
printf "please input 2 numbers:\n"
echo -e "$0 num1 num2"
exit
} #judge num
if [ $# -ne ]
then
print_usage
fi #judge num
[ -n "`echo $1|sed 's/[0-9]//g' `" -a -n "`echo $2|sed 's/[0-9]//g'`" ] &&\
{
echo "$1 $2 must be number" ;
exit
} #judge body
if [ $ -gt $ ]
then
echo "$1 > $2"
elif [ $ -eq $ ]
then
echo "$1 = $2"
else
echo "$1 < $2"
fi

9. nginx测试demo

10. 远程端口监控

 方案一:
nmap 检查 #!/bin/sh httpPortNum=`nmap 192.168.25.138 -p |grep open|wc -l`
if [ $httpPortNum -eq ]; then
echo "httpd is running..."
else
echo "httpd is not running..."
server httpd start
fi 方案二:
wget -T -q --spider http://192.168.25.138 &>/dev/null
echo $? 方案三:
curl -I -s www.baidu.com |head -|cut -d " " -f2
if [ -eq HTTPCODE ]
echo $? 实际生产测试:
#!/bin/sh
HTTPCODE=`curl -I -s www.baidu.com |head -|cut -d " " -f2`
[ -f /etc/init.d/functions ] && . /etc/init.d/functions || exit
if [ "$HTTPCODE" -eq "" ];then
action "BaiDu/Nginx Http Server is Ok" /bin/true
else
action "BaiDu/Nginx Http Server is Error" /bin/false
fi 方案四: -->手动输入IP进行判断
#!/bin/sh if [ $# -ne ]; then
echo "USAGE: $0 IPADDR"
exit
fi
HTTPCODE=`curl -I -s "$1"|head -|cut -d " " -f2`
[ -f /etc/init.d/functions ] && . /etc/init.d/functions || exit
if [ "$HTTPCODE" -eq "" ];then
action "BaiDu/Nginx Http Server " /bin/true
else
action "BaiDu/Nginx Http Server" /bin/false fi 方案五 -->优化nmap
#!/bin/sh if [ $# -ne ]; then
echo "USAGE: $0 IPADDR PORT"
exit
fi
HTTPCODE=`nmap $ -p $|sed -n '7p'|awk '{print $2}'` -->也可以统计数量是否为1
[ -f /etc/init.d/functions ] && . /etc/init.d/functions || exit
if [ "$HTTPCODE" == "open" ];then
action "$1 on $2 port server " /bin/true
else
action "$1 on $2 port server " /bin/false fi 方案六: echo -e "\n"|telnet www.baidu.com |grep Connected|wc -l -->可以执行完成第一个管道后执行换行命令 方案七:
nc -w www.baidu.com && echo ok

11. Mysql服务监控

 生成环境监控Mysqsl
方案1:过滤3306端口,查看是否启动正常
ps -ef|grep |grep -v grep -->不建议,因为不太准,有的vi也是有显示结果的
netstat -lnput|grep
netstat -lnput|grep |wc -l -->最常用的,如果为1,则表示开启,然后判读是否为1 if [ $port -eq ] 方案2;Mysql端口和进程同时存在,则服务正常
PORT=`netstat -lnput|grep |wc -l'`
PROCESS=`ps -ef|grep mysqld|grep -v grep|wc -l` 方案1:
#!/bin/sh
#Author: ftl
#Mysql Monitor PORT=`netstat -lnput|grep |awk -F '[ :]+' '{print $5}'` -->思路不是最佳
if [ $PORT -eq ];then -->最还用字符串判断 if [ "$PORT" == "" ]
echo "Mysql is Running ...."
else
service mysqld start
fi 方案2:
#!/bin/sh
#Author: ftl
#Mysql Monitor PORT=`netstat -lnput|grep |wc -l`
PROCESS=`ps -ef|grep mysqld|grep -v grep|wc -l`
#if [ $PORT -eq 1 -a $PROCESS -eq 1 ];then -->相等的
if [ $PORT -eq ] && [ $PROCESS -eq ];then
echo "Mysql is Running ...."
else
service mysqld start
fi 实际的解决:
#!/bin/sh
#Author: ftl
#Mysql Monitor PORT=`netstat -lnput|grep |wc -l`
PROCESS=`ps -ef|grep mysqld|grep -v grep|wc -l`
#if [ $PORT -eq 1 -a $PROCESS -eq 1 ];then -->相等的
if [ $PORT -eq ] && [ $PROCESS -eq ];then
echo "Mysql is Running ...."
else
service mysqld start
sleep
PORT=`netstat -lnput|grep |wc -l`
PROCESS=`ps -ef|grep mysqld|grep -v grep|wc -l`
if [ $PORT -eq ] && [ $PROCESS -eq ];then
echo "Mysql is Running ...."
else
while true
do
pkill mysqld >/dev/null >&
sleep
[ $? -ne ] && break
done
fi
service mysqld start && echo 'mysql is running....'
fi 方案3:模拟web服务器,根据mysql账户进行连接,然后根据返回在状态判断mysql是否启动
mysql -uroot -proot -h localhost -e "select version()"; -->查看mysql版本
#!/bin/sh
#Author: ftl
#Mysql Monitor MYSQL_VERSION=` mysql -uroot -proot -e "select version()" >/dev/null`
if [ $? -eq ];then
echo "Mysql is Running ...."
else
service mysqld start
fi 方案4:更专业的写法
用变量定义路径,
执行的脚本前面加上x判断 [ -x $MYSQL_SHELL ] >$LOG_DIR
mysql -uroot -proot -h localhost -e "select version()"; -->注意-h,用于远端的监控 方案5:最佳的,利用php/java来进行监控 <?php
$link_id=mysql_connect('db_etiantian','bbs','root') or mysql_error();
if($link_id){
echo "mysql is Ok ,Congratulation";
}else{
echo "Sorry,you can see logs of mysql";
echo mysql_error();
}
?>

12. 菜单联系

 #!/bin/sh
# menu list for ftl by ftl menu(){
cat <<END
.[install lamp]
.[install lnmp]
.[install mysql]
.[install nfs]
.[exit]
END
}
menu
read a
echo "you choose $a"

13. epxr小技巧

 .判断扩展名:

 if expr "hello.txt" : ".*\.txt"  -->判断文件拓展名是否为.txt  注意空格
->为真,则输出 显示匹配后的字符数,包括.txt
->为假,则输出非 .判断是否是整数
read -p "Please input"
expr $a + &>/dev/null
[ $? -eq ] && echo int || echo char

14. let监听服务

 #/bin/sh
#Function Monitor by ftl -- ServerMonitor(){
#Monitro status
timeout=
fails=
success=
while true
do
/usr/bin/wget --timeout=$timeout --tries= http://192.168.25.138 -q -0 /dev/null
if [ $? -ne ]
then
let fails+=;
success=
else
fails=
let success=
fi if [ $success -ge ]
then
exit
fi if [ $fails -ge ]
then
Critical="TMS is Wrong ,please Checking...."
echo ${Critical}|mutt -s "httpd down,please contact hhh@ftl.com"
fi
done }

15. 用source解析命令的使用

 [root@lamp01 omc]# echo 'dir=`date +%F`'>qq.sh
[root@lamp01 omc]# sh qq.sh
[root@lamp01 omc]# echo $dir [root@lamp01 omc]# bash qq.sh
[root@lamp01 omc]# echo $dir [root@lamp01 omc]# source qq.sh
[root@lamp01 omc]# echo $dir
--
[root@lamp01 omc]#
说明:source将原来shell里面的东西作为结果传递给当前的shell去显示

Linux 下Shell的学习3-优秀demo的更多相关文章

  1. Linux 下Shell的学习

    1.Shell学习 1.什么是Shell    shell是一个命令解析器,在操作系统的最外层,负责和用户对话,将用户的输入解释给操作系统,并处理各种各样的操作系统的输出结果.2.什么是shell脚本 ...

  2. Linux 下shell 编程学习脚手架

    linux body { font-family: Helvetica, arial, sans-serif; font-size: 14px; line-height: 1.6; padding-t ...

  3. linux下shell脚本学习

    在Linux系统中,虽然有各种各样的图形化接口工具,但是sell仍然是一个非常灵活的工具.Shell不仅仅是命令的收集,而且是一门非常棒的编程语言.您可以通过使用shell使大量的任务自动化,shel ...

  4. Linux 下Shell的学习2

    0. 查看帮助(比如内置功能)    man bash    -->变量处理大全 1.-计算变量长度的不同方法及不同方法的耗时对比    尽可能的用内置的命令处理,速度快        time ...

  5. Linux 下Shell的学习3-service编程

    1. vim /etc/init.d/nginx 2. chmod 755 /etc/init.d/nginx 3. service nginx status #!/bin/bash # nginx ...

  6. .Neter玩转Linux系列之四:Linux下shell介绍以及TCP、IP基础

    基础篇 .Neter玩转Linux系列之一:初识Linux .Neter玩转Linux系列之二:Linux下的文件目录及文件目录的权限 .Neter玩转Linux系列之三:Linux下的分区讲解 .N ...

  7. Unix和Linux下C语言学习指南

    转自:http://www.linuxdiyf.com/viewarticle.php?id=174074 Unix和Linux下C语言学习指南 引言 尽管 C 语言问世已近 30 年,但它的魅力仍未 ...

  8. 06 Linux下Shell介绍

    一.概述 每个人在成功登陆Linux后,系统会出现不同的提示符号,例如$,~,#等,然后你就可以开始输入需要的命令.若命令正确,系统就会依据命令的要求来执行,直到注销系统为止,在登陆到注销期间,输入的 ...

  9. Linux 下Shell变量,环境变量的联系与区别

    Linux下Shell变量,环境变量的联系与区别 by:授客 QQ:1033553122 1.  简介 linux下的变量可分成两种:Shell变量和环境变量. Shell变量,又称本地变量,包括私有 ...

随机推荐

  1. unity优化测试插件推荐:内存分析,数据监控,弱网模拟

    1.内存分析插件,unity官方出品 官方地址:https://bitbucket.org/Unity-Technologies/memoryprofiler 我整理的:https://downloa ...

  2. TreeMap红黑树

    Java TreeMap实现了SortedMap接口,也就是说会按照key的大小顺序对Map中的元素进行排序,key大小的评判可以通过其本身的自然顺序(natural ordering),也可以通过构 ...

  3. (转载)GRASP职责分配原则

    GRASP (职责分配原则) 要学习设计模式,有些基础知识是我们必须要先知道的,设计模式是关于类和对象的一种高效.灵活的使用方式,也就是说,必须先有类和对象,才能有设计模式的用武之地,否则一切都是空谈 ...

  4. 原来你是这样的http2......

    欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 本文由mariolu发表于云+社区专栏 序言 目前HTTP/2.0(简称h2)已经在广泛使用(截止2018年8月根据Alexa流行度排名的头 ...

  5. CSS选择器详解(二)通用选择器和高级选择器

    目录 通用选择器 高级选择器 子选择器 相邻兄弟选择器 属性选择器 通用选择器 通用选择器可以选择页面上的所有元素,并对它们应用样式,用 * 来表示. 语法: * { property1: value ...

  6. WCF WCF的宿主

    一.WCF服务应用程序与WCF服务库 我们在平时开发的过程中常用的项目类型有“WCF 服务应用程序”和“WCF服务库”. WCF服务应用程序,是一个可以执行的程序,它有独立的进程,WCF服务类契约的定 ...

  7. jQuery 自制上传头像插件-附带Demo实例(ajaxfileupload.js第三弹)

    这篇文章主要是对前两篇关于ajaxfileupload.js插件的文章 <ASP.NET 使用ajaxfileupload.js插件出现上传较大文件失败的解决方法(ajaxfileupload. ...

  8. 撩课-Python-每天5道面试题-第2天

    一. 简述编程过程中, 注释的作用? (1) 方便开发人员自己理清楚代码思路 因为开发人员在拿到一个需求时, 首先应该思考的是如何将需求问题, 分解成具体的实施步骤; 第一步干啥, 第二步干啥, 第三 ...

  9. Git基础--笔记

    0.取的项目的git仓库 有两种取得 Git 项目仓库的方法.第一种是在现存的目录下,通过导入所有文件来创建新的 Git 仓库. 第二种是从已有的 Git 仓库克隆出一个新的镜像仓库来 1.在工作目录 ...

  10. 学习Golang的步骤建议

    一.快速入门 通过快速入门可以宏观的了解Go相关知识.快速入门可以去学习 go-tour 国内可以访问的中文版的 go-tour 地址有下面一些: http://gotour.qizhanming.c ...