shell的应用实例
用户建立脚本
执行users_create.sh userfile passfile
建立userfile列表中的用户
设定userfile列表中的密码为passfile列表中的密码
当脚本后面跟的文件个数不足两时,报错
当文件行数不一致时报错
当文件不存在时报错
当用户存在时报错
11 #!/bin/bash
12
13 n=`awk 'BEGIN{N=0}{N++}END{print N}' /ost/userfile`
14 for Num in `seq 1 "$n"`
15 do
16 User_name=`sed -n ""$Num"p" /ost/userfile`
17 Passwd=`sed -n ""$Num"p" /ost/passfile`
18 useradd $User_name
19 echo $Passwd | passwd --stdin $User_name
20 done
服务自动部署示例
执行脚本lamp.sh
脚本执行后部署好论坛,并设定apache的网络接口为8080
改变httpd的接口
11 #!/bin/bash
12 [ -z $1 ] && {
13 echo please give a num for port
14 exit 1
15 }
16
17 sed "/^Listen/cListen\ $1" -i /etc/httpd/conf/httpd.conf
18 systemctl restart httpd
数据库备份
执行db_dump.sh westos(数据库密码)
脚本执行后会备份数据库中的所有库到/mnt/mysqldump目录中
备份文件名称为 “库名称.sql”当此文件存在时报错并询问动作
输入“S”跳过备份,当输入“B"时备份“库名称.sql”文件为“库名称_backup.sql”,当输入“O”时,覆盖源文件
11 #!/bin/bash
12 ACTION_CMD(){
13 read -p "
14 [S]kip [B]ackup [O]verwrite
15 please input action: "ACTION
16 ACTION=`echo $ACTION|tr 'A-Z' 'a-z'`
17 case $ACTION in
18 s)
19 ;;
20 b)
21 echo backup
22 ;;
23 o)
24 echo overwrite
25 ;;
26 exit)
27 echo bye
28 exit 0
29 ;;
30 *)
31 echo "error: please input [S] [B] [O]"
32 ACTION_CMD $1
33 esac
34 }
35 for DATABASE in hello westos linux
36 do
37 [ -e "/sing777/backup/$DATABASE" ] && {
38 ACTION_CMD
39 }||{
40
41 }
自动登陆脚本
执行auto_ssh.sh 172.25.254.177 redhat
172.25.254.177为ip
redhat 为密码
执行脚本后自动登陆172.25.254.177并保持登陆
11 #!/bin/bash
12 Auto_Connect()
13 {
14 /usr/bin/expect <<EOF |grep -E "authenticity|ECDSA|connecting|Warning|spawn|password" -v
15 set timeout 5
16 spawn ssh [email protected]$NUM "$1"
17 expect {
18 "yes/no" { send "yes\r";exp_continue }
19 "password:" { send "redhat\r" }
20 }
21 expect eof
22 EOF
23 }
24 for NUM in 177
25 do
26 ping -c1 -w1 172.25.254.$NUM &> /dev/null &&{
27 Max_Line=`awk 'BEGIN{N=0}{N++}END{print N}' $1`
28 for Line_Num in `seq 1 $Max_line`
29 do
30 USERNAME=`sed -n ${Line_Num}p $1`
31 PASSWORD=`sed -n ${Line_Num}p $2`
32 User_check=`Auto_Connect "useradd $USERNAME"`
33 [ -n "$User_check" ]&&{
34 echo $User_check
35 }||{
36 Auto_Connetion "echo $PASSWORD | passwd --stdin $USERNAME"
37 done
38 }|| echo 172.25.254.$NUM is down
40 done