案例1:批量生成随机字 符 文件名案例

使用for 循环在 /neo 目录下批量创建10个html文件,其中每个文件需要包含10个随机小写字母加固定字符串 neo创建的结果名称示例 如下:

[root@oldgirl C19]# ls /neo
apquvdpqbk_neo.html mpyogpsmwj_neo.html txynzwofgg_neo.html
bmqiwhfpgv_neo.html mtrzobsprf_neo.html vjxmlflawa_neo.html
jhjdcjnjxc_neo.html qeztkkmewn_neo.html
jpvirsnjld_neo.html ruscyxwxai_neo.html

参考如下:

# 生成随机数的方式:
echo $RANDOM # 随机数的范围: 0~32767
openssl rand -base64 10 # 10 表示要生成的随机数的长度
date +%s%N # 用时间做随机数
head /dev/urandom |cksum
uuidgen # 利用uuid
cat /proc/sys/kernel/random/uuid
mkpasswd # 需要先安装 expect ; yum install expect -y
l 总长度
d 数字个数
c 小写字母个数
C 大写字母个数
s 特殊字符个数 # 示例:
[root@m01 ~]# mkpasswd -l 20 -d 17 -C 1 -c 1 -s 1
1194S1242h756%909877 # 获取到随机10个小写字母
[root@m01 ~]# echo "OLDBOY$RANDOM"
OLDBOY31600
[root@m01 ~]# echo "OLDBOY$RANDOM"|md5sum
2b33f154112a2f371beba1600d24f246 -
[root@m01 ~]# echo "OLDBOY$RANDOM"|md5sum|tr 0-9 a-j
icfafgebagjaajeieifeifabgfhfeegj -
[root@m01 ~]# echo "OLDBOY$RANDOM"|md5sum|tr 0-9 a-j |cut -c 2-11
afbagebbdf # 获取到随机10个小写字母
[root@m01 ~]# [root@m01 ~]# mkpasswd -l 10 -d 0 -C 0 -c 10 -s 0 # 获取到随机10个小写字母
tkbviqfovu
[root@m01 ~]# echo "OLDBOY$RANDOM"|md5sum|tr 0-9 a-j |cut -c 2-11
echo "" | md5sum # 查看一个字符串的md5值
cat file | tr [0-9] [a-j] # 把文件中的数字0-9替换为a-j
cut -c 2-11 # -c参数表示 仅显示行中指定范围的字符 # 示例代码:
[root@m01 cases]# cat case01.sh
#!/bin/bash
##############################################################
# File Name: case01.sh
# Version: V1.0
# Author: neo
# Organization: anonymous
# Created Time : 2019-07-04 11:15:30
# Description:
##############################################################
path=/neo
[ -d $path ] || mkdir -p $path # 如果 /neo 目录不存在则创建 for n in {1..10}
do
random=`mkpasswd -l 10 -d 0 -C 0 -c 10 -s 0`
touch $path/${random}_neo.html
done
[root@m01 cases]# sh case01.sh
[root@m01 neo]# ll
total 0
-rw-r--r-- 1 root root 0 Jul 4 11:23 hqxdsueipv_neo.html
-rw-r--r-- 1 root root 0 Jul 4 11:23 jpiauceiiy_neo.html
-rw-r--r-- 1 root root 0 Jul 4 11:23 lagtetdxnu_neo.html
-rw-r--r-- 1 root root 0 Jul 4 11:23 ogkstnleki_neo.html
-rw-r--r-- 1 root root 0 Jul 4 11:23 qkljrkpckc_neo.html
-rw-r--r-- 1 root root 0 Jul 4 11:23 rpslndkrjc_neo.html
-rw-r--r-- 1 root root 0 Jul 4 11:23 snvcqbwlko_neo.html
-rw-r--r-- 1 root root 0 Jul 4 11:23 tuwsslvcgn_neo.html
-rw-r--r-- 1 root root 0 Jul 4 11:23 tzxismkjka_neo.html
-rw-r--r-- 1 root root 0 Jul 4 11:23 wlaroblbvi_neo.html
[root@m01 neo]#

案例2:批量改名特殊案例

将以上案例1中结果文件名中的 neo 字符串全部改成 Neomaple,最好用 for 循环实现并且将扩展名html全部改成大写

参考如下:

# 方式一:for 循环
[root@m01 cases]# cat case02.sh
#!/bin/bash
for file in `ls /neo/*.html`
do
mv $file /${file/neo.html/Neomaple.HTML}
done
[root@m01 cases]# # 方式二:awk
[root@m01 neo]# ls *.html|awk -F "neo.html" '{print "mv",$0,$1"Neomaple.HTML"}'
mv dbizjjvosl_neo.html dbizjjvosl_Neomaple.HTML
mv ezoiojifzy_neo.html ezoiojifzy_Neomaple.HTML
mv fanspikyqs_neo.html fanspikyqs_Neomaple.HTML
mv hmvkxpoyru_neo.html hmvkxpoyru_Neomaple.HTML
mv hymssbshwu_neo.html hymssbshwu_Neomaple.HTML
mv kgavlirhts_neo.html kgavlirhts_Neomaple.HTML
mv khxcbyrnnt_neo.html khxcbyrnnt_Neomaple.HTML
mv ntgtztpzsp_neo.html ntgtztpzsp_Neomaple.HTML
mv pfykhbwgyk_neo.html pfykhbwgyk_Neomaple.HTML
mv sybwbmnmyh_neo.html sybwbmnmyh_Neomaple.HTML
[root@m01 neo]# ls *.html|awk -F "neo.html" '{print "mv",$0,$1"Neomaple.HTML"}'|bash # 方式三:rename
[root@m01 neo]# rename "neo.html" "Neomaple.HTML" *.html # 把 neo.html 改成 Neomaple.HTML ;*.html 表示针对 以 html结尾的文件

案例3:批量创建特殊要求用户案例

批量创建10个系统帐号 neo01 - neo10 并设置密码(密码为随机数 ,要求字符和数字等混合)

# 分析:
1) 生成01~10的序列:
echo {01..10}
seq -w 10
2) 随机数:
openssl rand -base64 10
3) 创建用户和密码:
useradd neo01 # 创建用户
# 设置密码方法1:
echo 密码 |passwd --stdin 用户名
# 设置密码方法2:
chpasswd 命令
chpasswd 设置密码时,用户名和密码要遵守这种格式: 用户名:密码
4) for 循环 # 方式一:
[root@m01 cases]# cat case03.sh
#!/bin/bash
for n in {01..10}
do
passwd=`openssl rand -base64 10` # 要把随机密码保存到变量中
useradd neo$n
echo $passwd|passwd --stdin neo$n
echo -e "neo$n\t$passwd" >>/tmp/user.list # 把密码保存到文件中; echo -e 的作用是 解析 \t
done
[root@m01 cases]# sh case03.sh
Changing password for user neo01.
passwd: all authentication tokens updated successfully.
Changing password for user neo02.
passwd: all authentication tokens updated successfully.
Changing password for user neo03.
passwd: all authentication tokens updated successfully.
Changing password for user neo04.
passwd: all authentication tokens updated successfully.
Changing password for user neo05.
passwd: all authentication tokens updated successfully.
Changing password for user neo06.
passwd: all authentication tokens updated successfully.
Changing password for user neo07.
passwd: all authentication tokens updated successfully.
Changing password for user neo08.
passwd: all authentication tokens updated successfully.
Changing password for user neo09.
passwd: all authentication tokens updated successfully.
Changing password for user neo10.
passwd: all authentication tokens updated successfully.
[root@m01 cases]# cat /tmp/user.list
neo01 pFvlvG0NXpIvYg==
neo02 UPRO/U7uTxnJNw==
neo03 0xkAtO5U70ws5w==
neo04 wXR+K7fl+8i5wA==
neo05 7bt6b09wv5dw7Q==
neo06 AUNPXdRaJ8NUTA==
neo07 E+JPwENB7KXHUA==
neo08 1lZylckuf8rNlg==
neo09 ZD7qVwMfsPMvzg==
neo10 B3EgYyb/swvDow==
[root@m01 cases]# su - neo01
[neo01@m01 ~]$ su - neo02
Password:
[neo02@m01 ~]$ whoami
neo02
[neo02@m01 ~]$ # 方式二:
[root@m01 cases]# cat case0302.sh
#!/bin/bash
for n in `seq -w 11 15`
do
passwd=`openssl rand -base64 10` # 要把随机密码保存到变量中
useradd neo$n
echo "neo$n:$passwd" >>/tmp/chpasswd.log # 把用户名和密码以 用户名:密码 这种格式保存到 一个文件 chpasswd.log 中
done chpasswd </tmp/chpasswd.log # 把 /tmp/chpasswd.log 这个文件通过输出重定向 给 chpasswd 命令处理,由于 chpasswd.log 中是以 用户名:密码 格式保存的,所以 chpasswd 命令能直接处理
[root@m01 cases]# sh case0302.sh
[root@m01 cases]# cat /tmp/chpasswd.log
neo11:Ij76k7pbfyByZQ==
neo12:lmCPKpKoUP/UOg==
neo13:JNIfuo8wwXgEkA==
neo14:QkBxlLf6mhQP+g==
neo15:fbvtdTSu9yTySg==
[root@m01 cases]# su - neo11
[neo11@m01 ~]$ su - neo15
Password:
[neo15@m01 ~]$ # 方式三:
[root@m01 cases]# cat case0303.sh
#!/bin/bash
. /etc/init.d/functions if [ $UID -ne 0 ]
then
action "only root can execute this script" /bin/false
exit 1
fi for n in {12..17}
do
passwd=`openssl rand -base64 10`
if `! grep -w "neo$n" /etc/passwd &>/dev/null` # grep -w 表示精确匹配;grep 如果获取到相应结果,则grep命令的执行结果为0(真),反之则执行结果为1(假);if `命令表达式 &>/dev/null` 时是判断 命令表达式的执行结果是否为真(由于只看执行结果,此时加 &>/dev/null,否则 if 字符串 会报错)
then
# \ 表示换行符
useradd neo$n &>/dev/null && \
echo $passwd|passwd --stdin neo$n &>/dev/null && \
echo -e "neo$n\t$passwd" >>/tmp/user.list && \
action "neo$n added successfully" /bin/true
else
action "neo$n exists already" /bin/false
fi
done
[root@m01 cases]# sh case0303.sh
neo12 exists already [FAILED]
neo13 exists already [FAILED]
neo14 exists already [FAILED]
neo15 exists already [FAILED]
neo16 added successfully [ OK ]
neo17 added successfully [ OK ]
[root@m01 cases]#

案例4: 扫描网络内存活主机案例

写一个Shell脚本,判断 10.0.0.0/24 网络里,当前在线的IP有哪些

1) ping 命令
[root@m01 ~]# ping -c 2 -i 1 -w 3 10.0.0.61
PING 10.0.0.61 (10.0.0.61) 56(84) bytes of data.
64 bytes from 10.0.0.61: icmp_seq=1 ttl=64 time=0.079 ms
64 bytes from 10.0.0.61: icmp_seq=2 ttl=64 time=0.052 ms --- 10.0.0.61 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1005ms
rtt min/avg/max/mdev = 0.052/0.065/0.079/0.015 ms ping 命令:
-c ping 的次数
-i ping 时间间隔(s)
-w ping 的总共的时长(s) 2) nmap命令
nmap -sP 10.0.0.0/24 # 方式一: ping
[root@m01 cases]# cat case0401.sh
#!/bin/bash
##############################################################
# File Name: case0401.sh
# Version: V1.0
# Author: neo
# Organization: anonymous
# Created Time : 2019-07-05 00:54:20
# Description:
##############################################################
for n in {1..254}
do
{
if `ping -c 1 -w 3 10.0.0.$n &>/dev/null` # ping 通为true
then
echo "10.0.0.$n is up"
else
echo "10.0.0.$n is down"
fi
} & # {} & 表示 {} 里面的代码并发执行;此处表示批量 ping
done
[root@m01 cases]# # 方式二: nmap
[root@m01 ~]# nmap -sP 10.0.0.0/24 Starting Nmap 5.51 ( http://nmap.org ) at 2019-07-05 01:34 CST
Nmap scan report for 10.0.0.61
Host is up.
Nmap scan report for 10.0.0.253
Host is up (0.0032s latency).
MAC Address: 00:50:56:C0:00:08 (VMware)
Nmap scan report for 10.0.0.254
Host is up (0.00081s latency).
MAC Address: 00:50:56:EA:79:FB (VMware)
Nmap done: 256 IP addresses (3 hosts up) scanned in 8.36 seconds
[root@m01 ~]# nmap -sP 10.0.0.0/24|awk '/Nmap scan report for/{print $NF}' # $NF 表示的最后一个Field(列),即输出最后一个字段的内容
10.0.0.61
10.0.0.253
10.0.0.254
[root@m01 ~]#

案例5:数据库的备份

# 案例5.1:MySQL 数据库分库备份
# 常规方法:
mysqldump -B oldboy oldgirl test|gzip >bak.sql.gz # --databases, -B: 用于备份多个数据库,如果没有该选项,mysqldump把第一个名字参数作为数据库名,后面的作为表名。使用该选项,mysqldum把每个名字都当作为数据库名。 # 分库备份:
mysqldump -B oldboy |gzip >bak.sql.gz
mysqldump -B oldgirl |gzip >bak.sql.gz
mysqldump -B test|gzip >bak.sql.gz # 相关命令:
mysqldump -uroot -p123456 db_name table1 table2 |gzip >bak.sql.gz # mysqldump 命令中只有第一个参数 db_name 是库名,后面跟的所有参数都是表名 # 命令操作如下:
[root@db01 application]# /application/mysql/bin/mysql -uroot -p123456 -e "show databases;" # 命令行获取数据库名
Warning: Using a password on the command line interface can be insecure.
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| test |
| wordpress |
+--------------------+
[root@web01 ~]# /application/mysql/bin/mysql -uroot -p123456 -e "show databases;"|grep -v _schema # 去掉包含 _schema 的数据库
Warning: Using a password on the command line interface can be insecure.
Database
mysql
test
wordpress
[root@web01 ~]# /application/mysql/bin/mysql -uroot -p123456 -e "show databases;"|grep -v _schema|sed 1d # 去掉第一行的 Database
Warning: Using a password on the command line interface can be insecure.
mysql
test
wordpress
[root@web01 ~]# /application/mysql/bin/mysql -uroot -p123456 -e "show databases;" 2>/dev/null|grep -v _schema|sed 1d # 2>/dev/null 表示错误信息不输出
mysql
test
wordpress
[root@web01 ~]# # 示例代码如下:
[root@web01 cases]# cat backup-db.sh
#/bin/bash
path=/backup [ -d $path ] || mkdir -p $path for dbname in `/application/mysql/bin/mysql -uroot -p123456 -e "show databases;" 2>/dev/null |grep -v _schema|sed 1d`
do
/application/mysql/bin/mysqldump -uroot -p123456 -B $dbname|gzip >$path/${dbname}_$(date +%F).sql.gz 2>/dev/null
done
[root@web01 cases]# sh backup-db.sh
Warning: Using a password on the command line interface can be insecure.
Warning: Using a password on the command line interface can be insecure.
Warning: Using a password on the command line interface can be insecure.
[root@web01 cases]# [root@web01 backup]# ll
total 372
-rw-r--r-- 1 root root 179858 Jul 6 00:48 mysql_2019-07-06.sql.gz
-rw-r--r-- 1 root root 517 Jul 6 00:48 test_2019-07-06.sql.gz
-rw-r--r-- 1 root root 193084 Jul 6 00:48 wordpress_2019-07-06.sql.gz
[root@web01 backup]# # 案例5.2:MySQL 数据库分库分表备份
# 相关命令:
mysqldump oldboy test test1|gzip >bak.sql.gz
# 1、 oldboy 库名
# 2、 test、test1 都是表名 [root@db01 ~]# /application/mysql/bin/mysql -uroot -p123456 -e "show tables from wordpress;" # 命令行获取某个数据库下的表名
Warning: Using a password on the command line interface can be insecure.
+-----------------------+
| Tables_in_wordpress |
+-----------------------+
| wp_commentmeta |
| wp_comments |
| wp_links |
| wp_options |
| wp_postmeta |
| wp_posts |
| wp_term_relationships |
| wp_term_taxonomy |
| wp_termmeta |
| wp_terms |
| wp_usermeta |
| wp_users |
+-----------------------+
[root@web01 ~]# /application/mysql/bin/mysql -uroot -p123456 -e "show tables from wordpress;"|sed 1d
Warning: Using a password on the command line interface can be insecure.
wp_commentmeta
wp_comments
wp_links
wp_options
wp_postmeta
wp_posts
wp_term_relationships
wp_term_taxonomy
wp_termmeta
wp_terms
wp_usermeta
wp_users
[root@db01 ~]# # 示例代码如下:
[root@web01 cases]# cat backup-db-tb.sh
#/bin/bash
path=/backup [ -d $path ] || mkdir -p $path
mysql="/application/mysql/bin/mysql -uroot -p123456"
mysqldump="/application/mysql/bin/mysqldump -uroot -p123456" for dbname in `$mysql -e "show databases;" 2>/dev/null |grep -v _schema|sed 1d` # 先获取数据库的名字
do
for tname in `$mysql -e "show tables from $dbname;" 2>/dev/null |sed 1d` # 再获取表名
do
if [ $dbname = "mysql" ]
then
$mysqldump --skip-lock-tables $dbname $tname|gzip >$path/${dbname}-${tname}_$(date +%F).sql.gz 2>/dev/null # 跳过 mysql 这个数据库 中的锁表
else
$mysqldump $dbname $tname|gzip >$path/${dbname}-${tname}_$(date +%F).sql.gz 2>/dev/null
fi
done
done
[root@web01 cases]#

案例6:ssh免密密钥批量分发文件脚本

有3台机器,61、7 和 8,采用ssh免密密钥实现从61主机到其它两台机器无密码登陆后,写脚本实现从61主机批量分发任意文件到另外两台机器上任意目录下

# 先生成、分发密钥:
[root@m01 ~]# ssh-keygen -t dsa # 生成密钥
Generating public/private dsa key pair.
Enter file in which to save the key (/root/.ssh/id_dsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_dsa.
Your public key has been saved in /root/.ssh/id_dsa.pub.
The key fingerprint is:
91:05:b6:09:9a:eb:cd:18:3f:b6:cf:b9:dd:ec:ef:fd root@m01
The key's randomart image is:
+--[ DSA 1024]----+
| . o.. |
| o o = |
| o = |
| . . |
| o S |
| . * |
| o * |
| . + o o . |
| ..=...+oo E|
+-----------------+
[root@m01 ~]# ll ~/.ssh/
total 8
-rw------- 1 root root 668 Jul 6 10:53 id_dsa
-rw-r--r-- 1 root root 598 Jul 6 10:53 id_dsa.pub
-rw-r--r-- 1 root root 0 Jul 6 10:13 known_hosts
[root@m01 ~]# ll ~/.ssh/
total 8
-rw------- 1 root root 668 Jul 6 10:53 id_dsa
-rw-r--r-- 1 root root 598 Jul 6 10:53 id_dsa.pub
-rw-r--r-- 1 root root 0 Jul 6 10:13 known_hosts
[root@m01 ~]# for n in 7 8;do ssh-copy-id -i /root/.ssh/id_dsa.pub 172.16.1.$n;done # 分发公钥: ssh-copy-id -i /root/.ssh/id_dsa.pub 172.16.1.7
The authenticity of host '172.16.1.7 (172.16.1.7)' can't be established.
RSA key fingerprint is 22:07:4d:36:3c:5e:eb:46:80:a2:ef:40:45:8c:93:46.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '172.16.1.7' (RSA) to the list of known hosts.
root@172.16.1.7's password:
Now try logging into the machine, with "ssh '172.16.1.7'", and check in: .ssh/authorized_keys to make sure we haven't added extra keys that you weren't expecting. The authenticity of host '172.16.1.8 (172.16.1.8)' can't be established.
RSA key fingerprint is 22:07:4d:36:3c:5e:eb:46:80:a2:ef:40:45:8c:93:46.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '172.16.1.8' (RSA) to the list of known hosts.
root@172.16.1.8's password:
Now try logging into the machine, with "ssh '172.16.1.8'", and check in: .ssh/authorized_keys to make sure we haven't added extra keys that you weren't expecting. [root@m01 ~]# for n in 7 8;do echo 172.16.1.$n && ll ~/.ssh/ ;done
172.16.1.7
total 12
-rw------- 1 root root 668 Jul 6 10:53 id_dsa
-rw-r--r-- 1 root root 598 Jul 6 10:53 id_dsa.pub
-rw-r--r-- 1 root root 784 Jul 6 11:00 known_hosts
172.16.1.8
total 12
-rw------- 1 root root 668 Jul 6 10:53 id_dsa
-rw-r--r-- 1 root root 598 Jul 6 10:53 id_dsa.pub
-rw-r--r-- 1 root root 784 Jul 6 11:00 known_hosts
[root@m01 ~]# # 示例代码如下:
[root@m01 cases]# cat case06-distribute-file.sh
#!/bin/bash
##############################################################
# File Name: case06-distribute-file.sh
# Version: V1.0
# Author: neo
# Organization: anonymous
# Created Time : 2019-07-06 11:09:01
# Description:
##############################################################
. /etc/init.d/functions if [ $# -ne 2 ]
then
echo "Usage:$0 localdir remotedir"
exit 1
fi for n in 7 8 9
do
scp -rp $1 172.16.1.$n:$2 &>/dev/null
if [ $? -eq 0 ]
then
action "distribute 172.16.1.$n successfully" /bin/true
else
action "distribute 172.16.1.$n failed" /bin/false
fi
done
[root@m01 cases]# sh case06-distribute-file.sh
Usage:case06-distribute-file.sh localdir remotedir
[root@m01 cases]# sh case06-distribute-file.sh /neo /neozheng/
distribute 172.16.1.7 successfully [ OK ]
distribute 172.16.1.8 successfully [ OK ]
distribute 172.16.1.9 failed [FAILED] # 失败原因是 9主机没开
[root@m01 cases]#

案例7:破解 RANDOM 随机数案例

已知下面的字符串是通过 RANDOM 随机数变量 md5sum 后,再截取一部分连续字符串的结果,请破解这些字符串对应的使用 md5sum 处理前的 RANDOM 对应的数字
21029299
00205d1c
a3da1677
1f6d12dd
890684b # 分析:
1) RANDOM随机数的范围 0~32767,就需要把 0~32767 都用 md5sum 加密 >md5.log
2) 比较:grep "1f6d12dd" md5.log |wc -l [root@m01 ~]# array=(
> 21029299
> 00205d1c
> a3da1677
> 1f6d12dd
> 890684b
> )
[root@m01 ~]# echo ${array[*]}
21029299 00205d1c a3da1677 1f6d12dd 890684b
[root@m01 ~]# echo ${array[*]}|tr " " "|"
21029299|00205d1c|a3da1677|1f6d12dd|890684b # 把 数组中的元素以 “或”符号 | 分隔
[root@m01 ~]# # 示例代码如下:
[root@m01 cases]# cat case07-decode-random.sh
#!/bin/bash
##############################################################
# File Name: case07-decode-random.sh
# Version: V1.0
# Author: neo
# Organization: anonymous
# Created Time : 2019-07-06 12:54:04
# Description:
##############################################################
array=(
21029299
00205d1c
a3da1677
1f6d12dd
890684b
) function Funcmd5(){
for n in {1..32767}
do
echo -e "$n\t`echo $n|md5sum`" >>/tmp/md5.log &
done
} function FuncJudge(){
char=`echo ${array[*]}|tr " " "|"`
egrep $char /tmp/md5.log
} function main(){
Funcmd5
FuncJudge
}
main
[root@m01 cases]# sh case07-decode-random.sh
1346 00205d1cbbeb97738ad5bbdde2a6793d -
7041 1f6d12dd61b5c7523f038a7b966413d9 -
10082 890684ba3685395c782547daf296935f -
25345 a3da1677501d9e4700ed867c5f33538a -
25667 2102929901ee1aa769d0f479d7d78b05 -
[root@m01 cases]#

案例8:批量检查多个网站地址是否正常

批量检查多个网站地址是否正常
要求:
1、使用 shell 数组方法实现,检测策略尽量模拟用户访问 。
2、每 10 秒钟做一次所有的检测,无法访问的输出报警。
3、待检测的地址如下
http://blog.oldboyedu.com
http://blog.etiantian.org
http://oldboy.blog.51cto.com
http://10.0.0.7 # 示例代码如下:
[root@m01 cases]# cat case08-checkurl.sh
#!/bin/bash
##############################################################
# File Name: case08-checkurl.sh
# Version: V1.0
# Author: neo
# Organization: anonymous
# Created Time : 2019-07-06 19:03:48
# Description:
##############################################################
. /etc/init.d/functions array=(
http://blog.oldboyedu.com
http://blog.etiantian.org
http://oldboy.blog.51cto.com
http://10.0.0.7
) function CheckUrl(){
wget -t 2 -T 5 -o /dev/null -q $1
if [ $? -eq 0 ]
then
action "$1 is up" /bin/true
else
action "$1 is down" /bin/false
fi
} function HandleCheck(){
for url in ${array[*]}
do
CheckUrl $url
done
} function main(){
while true
do
HandleCheck
sleep 10
done
}
main
[root@m01 cases]# sh case08-checkurl.sh
http://blog.oldboyedu.com is up [ OK ]
http://blog.etiantian.org is down [FAILED]
http://oldboy.blog.51cto.com is up [ OK ]
http://10.0.0.7 is down [FAILED]
...
[root@m01 cases]#

案例10:开发MySQL服务启动停止脚本

要求:用函数、case语句和if语句等实现

# 解答:
/etc/init.d/mysqld {start|stop|restart} # 分析:
1. 启动:
/bin/bash mysqld_safe --user=mysql & 2. 停止:
mysqladmin -u用户名 -p密码 shutdown
killall
pkill
kill pid (推荐) # 示例代码如下:
[root@web01 cases]# cat mysqld.sh
#!/bin/bash
# chkconfig: 2345 20 80
# description: mysql start and stop script
##############################################################
# File Name: mysqld.sh
# Version: V1.0
# Author: neo
# Organization: anonymous
# Created Time : 2019-07-07 13:44:57
# Description:
##############################################################
lockfile=/var/lock/subsys/mysqld # 先定义一个锁文件
mysqld_pid_file_path="/application/mysql/data/${HOSTNAME}.pid" # 定义 mysql 进程号的路径 . /etc/init.d/functions function start(){
/bin/sh /application/mysql/bin/mysqld_safe --user=mysql &>/dev/null &
retval=$?
if [ $retval -eq 0 ]
then
action "mysql startup ok" /bin/true
touch $lockfile # 启动成功后,就创建一个锁文件
return $retval
else
action "mysql startup failed" /bin/false
return $retval
fi
} function stop(){
if test -s $mysqld_pid_file_path # -s ---> 判断文件是否存在且不为空
then
mysqld_pid=`cat $mysqld_pid_file_path`
if (kill -0 $mysqld_pid &>/dev/null) # kill -0 进程号 ---> 判断该进程号对应的服务是否存在;存在则echo $?返回0,不存在返1
then
kill $mysqld_pid
retval=$?
if [ $retval -eq 0 ]
then
action "mysql stop ok" /bin/true
\rm -f $lockfile # 停止成功后就删除锁文件
return $retval
else
action "mysql stop failed" /bin/false
return $retval
fi else # 此种情况是:$mysqld_pid 对应的 mysqld 服务不存在
action "mysqld service is not running"
return 2
fi else # 此种情况是: $mysqld_pid_file_path 对应的路径不存在
action "$mysqld_pid_file_path not exist, or mysqld not startup" /bin/false
return 3
fi
} case "$1" in
start)
start
retval=$? # 接收 start 的执行结果并赋值给 retval 作为返回值
;;
stop)
stop
retval=$?
;;
restart)
stop && sleep 1 && start
retval=$?
;;
*)
echo "Usage:$0 {start|stop|restart}"
exit 1
esac
exit $retval # 把上面的执行结果返回给脚本外面
[root@web01 cases]# # mysqld.sh 脚本测试
[root@web01 cases]# sh mysqld.sh
Usage:mysqld.sh {start|stop|restart}
[root@web01 cases]# sh mysqld.sh start
mysql startup ok [ OK ]
[root@web01 cases]# lsof -i:3306
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
mysqld 4084 mysql 16u IPv6 19781 0t0 TCP *:mysql (LISTEN)
[root@web01 cases]# sh mysqld.sh restart
mysql stop ok [ OK ]
mysql startup ok [ OK ]
[root@web01 cases]# lsof -i:3306
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
mysqld 4224 mysql 16u IPv6 20084 0t0 TCP *:mysql (LISTEN)
[root@web01 cases]# sh mysqld.sh stop
mysql stop ok [ OK ]
[root@web01 cases]# lsof -i:3306
[root@web01 cases]# # 给自写的 mysqld.sh 脚本 加执行权限
[root@web01 cases]# cp mysqld.sh /etc/init.d/mysqld_neo
[root@web01 cases]# ll /etc/init.d/mysqld_neo
-rw-r--r-- 1 root root 2521 Jul 7 14:29 /etc/init.d/mysqld_neo
[root@web01 cases]# chmod +x /etc/init.d/mysqld_neo
[root@web01 cases]# ll /etc/init.d/mysqld_neo
-rwxr-xr-x 1 root root 2521 Jul 7 14:29 /etc/init.d/mysqld_neo
[root@web01 cases]#

案例11:单词及字母去重排序案例

用shell处理以下内容
1、按单词出现频率降序排序
2、按字母出现频率降序排序 the squid project provides a number of resources to assist users design,implement and support squid installations. Please browse the documentation and support sections for more infomation, by oldboy training. # 按单词出现频率降序排序:
# 方法一:
[root@m01 ~]# a="the squid project provides a number of resources to assist users design,implement and support squid installations. Please browse the documentation and support sections for more infomation, by oldboy training."
[root@m01 ~]# echo $a|tr " ,." "\n"|awk '!/^$/{h[$1]++}END{for(word in h) print h[word],word}'|sort -rn
2 the
2 support
2 squid
2 and
1 users
1 training
1 to
1 sections
1 resources
1 provides
1 project
1 Please
1 oldboy
1 of
1 number
1 more
1 installations
1 infomation
1 implement
1 for
1 documentation
1 design
1 by
1 browse
1 assist
1 a
[root@m01 ~]# # 方法二:
[root@m01 ~]# sentence="the squid project provides a number of resources to assist users design,implement and support squid installations. Please browse the documentation and support sections for more infomation, by oldboy training."
[root@m01 ~]# echo $sentence |awk -F "[ ,.]+" '{for(i=1;i<=NF;i++)array[$i]++}END{for(key in array)print array[key],key}'|sort -rn
2 the
2 support
2 squid
2 and
1 users
1 training
1 to
1 sections
1 resources
1 provides
1 project
1 Please
1 oldboy
1 of
1 number
1 more
1 installations
1 infomation
1 implement
1 for
1 documentation
1 design
1 by
1 browse
1 assist
1 a
1
[root@m01 ~]# # 注意: awk 能以 空 作为 分隔符 # 按字母出现频率降序排序:
# 方法一:
[root@m01 ~]# sentence="the squid project provides a number of resources to assist users design,implement and support squid installations. Please browse the documentation and support sections for more infomation, by oldboy training."
[root@m01 ~]# echo $sentence |grep -o "[^ ,.]"|awk '{h[$1]++}END{for(char in h) print h[char],char}'|sort -rn
19 s
18 o
17 e
15 t
14 n
14 i
12 r
10 a
8 u
8 d
7 p
6 m
5 l
4 c
4 b
3 f
2 y
2 q
2 h
2 g
1 w
1 v
1 P
1 j
[root@m01 ~]# # grep -o 表示 只输出匹配的内容:
grep -o "[^ ,\.]" ---> [^] 表示 只输出匹配的选项,所以 该命令的意思是: 排除 空格 逗号 和 点 # 方法二:
# 注意: awk 可以用空作为分隔符
[root@m01 ~]# echo $sentence|sed 's#[ ,.]##g' # 利用 sed 把 空格 逗号 和 点 替换为 空
thesquidprojectprovidesanumberofresourcestoassistusersdesignimplementandsupportsquidinstallationsPleasebrowsethedocumentationandsupportsectionsformoreinfomationbyoldboytraining
[root@m01 ~]# echo $sentence |sed "s#[ ,.]##g"|awk -F "" '{for(i=1;i<=NF;i++)array[$i]++}END{for(key in array)print array[key],key}'
8 u
2 h
1 v
14 i
1 w
1 P
1 j
2 y
5 l
6 m
14 n
10 a
4 b
18 o
4 c
7 p
8 d
2 q
12 r
17 e
3 f
19 s
2 g
15 t
[root@m01 ~]# # awk -F "" ---> 表示 以空作为分隔符
# {for(i=1;i<=NF;i++)array[$i]++} ---> 把 echo $sentence |sed "s#[ ,.]##g" 得到的那个字符串进行 横向处理,即把每个字母作为一列;横向处理字符串从来得到一个数组 array;i 表示第i列 # 最终命令:
[root@m01 ~]# echo $sentence |sed "s#[ ,.]##g"|awk -F "" '{for(i=1;i<=NF;i++)array[$i]++}END{for(key in array)print array[key],key}'|sort -rn
19 s
18 o
17 e
15 t
14 n
14 i
12 r
10 a
8 u
8 d
7 p
6 m
5 l
4 c
4 b
3 f
2 y
2 q
2 h
2 g
1 w
1 v
1 P
1 j
[root@m01 ~]#

Linux(17):Shell编程(4)的更多相关文章

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

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

  2. Linux下Shell编程

    Linux的shell编程 1.什么是shell? 当一个用户登录Linux系统之后,系统初始化程序init就为每个用户执行一个称为shell(外壳)的程序. shell就是一个命令行解释器,它为用户 ...

  3. 【Hadoop离线基础总结】linux的shell编程

    linux的shell编程 基本了解 概述 Shell是一个用C语言编写的程序,通过shell用户可以访问操作系统内核服务,它类似于DOS下的command和后来的cmd.exe.Shell既是一种命 ...

  4. Linux学习笔记(17) Shell编程之基础

    1. 正则表达式 (1) 正则表达式用来在文件中匹配符合条件的字符串,正则是包含匹配.grep.awk.sed等命令可以支持正则表达式:通配符用来匹配符合条件的文件名,通配符是完全匹配.ls.find ...

  5. linux中shell编程

    shell编程 1 echo -e 识别\转义符 \a \b \t \n \x十六进制 \0八进制 等等 #!/bin/bash echo -e "hello world" 执行脚 ...

  6. Linux之shell编程的基本使用

    1.Shell shell是一个命令行解释器,它为用户提供了一个向 Linux 内核发送请求以便运行程序的系统级程序 2.shell编程打印hello world 2.1 代码部分 #!/bin/ba ...

  7. linux下shell编程示例-获取进程id

    今天初步学习了一下linux下的shell编程,简单记录一下测试用例 1.编辑shell脚本文件如下: #!/bin/bashecho "hello bash linux"echo ...

  8. linux之shell编程基本语法

    Shell是用户与内核进行交互操作的一种接口,目前最流行的Shell称为bash Shell.Shell也是一门编程语言<解释型的编程语言>,即shell脚本<就是在用linux的s ...

  9. Linux学习——shell编程之变量

    shell编程之变量:Linux shell编程基础中的变量. 包括Bash变量的分类和各变量的详细使用,如:用户自定义变量.环境变量.语系变量.位置参数变量和预定义变量. 1:什么是Bash变量? ...

  10. 3. Linux的shell编程

    Shell 是一个用 C 语言编写的程序, 通过 Shell 用户可以访问操作系统内核服务.它类似于 DOS 下的 command 和后来的 cmd.exe.Shell 既是一种命令语言,又是一种程序 ...

随机推荐

  1. win7远程连接ubuntu,出现灰屏解决方法

      问题: win7远程虚拟机ubuntu 12.04出现灰色屏幕 打开windows自带的远程桌面连接.输入ubuntu虚拟机的IP地址 可以连接上,输入username和password 点击OK ...

  2. 哨兵模式java实例

    /** * 测试Redis哨兵模式 * @author liu */ public class TestSentinels { @SuppressWarnings("resource&quo ...

  3. Constructor、Method、Field 源码阅读

    AnnotatedElement /** * AnnotatedElement 接口表示目前正在此 VM 中运行的应用程序的一个已注解元素[类.方法.属性]. * 该接口允许反射性地读取注解.此接口中 ...

  4. Workflow-Microsoft:Windows Workflow Foundation

    ylbtech-Workflow-Microsoft:Windows Workflow Foundation 1. Windows Workflow Foundation返回顶部 1.1. Windo ...

  5. 实用的60个CSS代码片段[下]

    31.有趣的& .amp { font-family: Baskerville, 'Goudy Old Style', Palatino, 'Book Antiqua', serif; fon ...

  6. 爬虫 lxml 模块

    Xpath 在 XML 文档中查找信息的语言, 同样适用于 HTML 辅助工具 Xpath Helper Chrome插件  快捷键 Ctrl + shift + x XML Quire xpath ...

  7. netcore kafka操作

    安装使用: 1:下载nuget包 Confluent.Kafka librdkafka.redist System.Runtime.CompilerServices.Unsafe 基于.net实现ka ...

  8. freetye2使用

    使用环境和版本:qt ubuntu 16.04   freetype-2.10.0 1.下载 https://sourceforge.net/projects/freetype/files/freet ...

  9. I'm using Python 2.7.2 ImportError No module named bz2

    安装mongodb的时候 提示错误 这是因为同时装了python2.6和2.7的缘故 sudo cp /usr/lib64/python2.6/lib-dynload/bz2.so /usr/loca ...

  10. Django-ORM之ForeignKey的使用-多对一关系

    ForeignKey使用俩表示两张表多对一关系的外键,外键字段要定义在多属性的表中. 定义外键时,to的表可以直接写类名,但是需要注意类的定义顺序:也可以写字符串式的类名,这样就可以忽略class类的 ...