Linux Shell 经典实例(1-30)

目  录

1、如何向脚本传递参数

2、如何在脚本中使用参数

3、获得脚本文件名

4、获得文件最后一行

5、获得文件第一行

6、如何获得每行第三个参数

7、for循环遍历目录

8、while循环

9、until循环

10、拼接字符串

11、函数相加

12、判断某个文件存在

13、获得文本的第10行 

14、 管道与bc预算

15、检查命令是否执行成功,0代表成功,非0都是执行失败。

16、传参检查

17、定期备份日志

18、一键安装LAMP

19、监听内存及磁盘容量发告警邮件

20、发邮件

21、猜数字游戏

22、校验权限自动部署vsftp

23、添加用户

24、输入三个数并进行升序排序

25、剪刀石头布

26、主机状态扫描 

27、九九表

28、监控网卡ens160手法数据 

29、批量添加用户(默认密码)

30、批量添加用户(带密码)


shell编程就是对一堆Linux命令的逻辑化处理。

就好比:

       excel中的vba

       window中的批处理

       word中的宏

总之就是将机械重复的操作步骤,打包成一个自动运行的脚本,不用每次都人工操作了。

1、如何向脚本传递参数


[wulei@obj02 ~]$ sudo sh ./show1.sh "aa"
aa
[wulei@obj02 ~]$ sudo sh ./show0.sh "aa" 
./show0.sh


[wulei@obj02 ~]$ sudo sh ./show0.sh 1.txt
./show0.sh
[wulei@obj02 ~]$ sudo sh ./show1.sh 1.txt 
1.txt
[wulei@obj02 ~]$ 


#源码展示
[wulei@obj02 ~]$ cat show0.sh 
#!/bin/bash
echo $0

[wulei@obj02 ~]$ cat show1.sh 
#!/bin/bash
echo $1

[wulei@obj02 ~]$ cat 1.txt 
I'm 1.txt
[wulei@obj02 ~]$ 

2、如何在脚本中使用参数

第一个参数 : $1,第二个参数 : $2,其中$0就是脚本本身


# 执行
[wulei@obj02 ~]$ sudo sh copy.sh 1.txt /tmp/

# 检查
[wulei@obj02 ~]$ ll /tmp/ |grep 1.txt   
-rw-r--r--. 1 root  root       10 Apr 11 00:36 1.txt


# 源码
[wulei@obj02 ~]$ cat copy.sh 
#!/bin/bash
cp $1 $2
[wulei@obj02 ~]$ 

3、获得脚本文件名

使用$0就可以获得脚本文件名

[root@obj02 wulei]# ./selfname.sh 
./selfname.sh
[root@obj02 wulei]# sh selfname.sh 
selfname.sh

#源码
[root@obj02 wulei]# cat selfname.sh 
#!/bin/bash
echo $0

4、获得文件最后一行

[wulei@obj02 ~]$ tail -1 1.txt 
the end

[wulei@obj02 ~]$ cat 1.txt 
I'm 1.txt
the end

5、获得文件第一行

[wulei@obj02 ~]$ head -1 1.txt 
I'm 1.txt
[wulei@obj02 ~]$ cat 1.txt 
I'm 1.txt
the end

6、如何获得每行第三个参数

[wulei@obj02 ~]$ cat /etc/passwd |awk -F ":" '{print $3}'
0
1
2
3
4
5
6
7
8
11
12
14
99
......

7、for循环遍历目录

[wulei@obj02 ~]$ ll
total 28
-rw-rw-r--. 1 wulei wulei 2437 Apr 11 01:00 1.txt
-rw-r--r--. 1 root  root    15 Apr 11 00:48 argsnum.sh
-rw-rw-r--. 1 wulei wulei   21 Apr 11 00:35 copy.sh
drwxr-xr-x. 2 wulei wulei    6 Mar 27 04:33 Desktop
drwxr-xr-x. 2 wulei wulei    6 Mar 27 04:33 Documents
drwxr-xr-x. 2 wulei wulei    6 Mar 27 04:33 Downloads
drwxr-xr-x. 2 wulei wulei    6 Mar 27 04:33 Music
drwxrwxr-x. 2 wulei wulei   26 Mar 30 22:44 notes
drwxr-xr-x. 2 wulei wulei    6 Mar 27 04:33 Pictures
drwxr-xr-x. 2 wulei wulei    6 Mar 27 04:33 Public
-rwxrwxr-x. 1 wulei wulei   20 Apr 11 00:43 selfname.sh
-rw-rw-r--. 1 wulei wulei   20 Apr 11 00:27 show0.sh
-rw-rw-r--. 1 wulei wulei   20 Apr 11 00:27 show1.sh
drwxr-xr-x. 2 wulei wulei    6 Mar 27 04:33 Templates
-rw-rw-r--. 1 wulei wulei   33 Apr 11 00:54 th3perlin.sh
drwxr-xr-x. 2 wulei wulei    6 Mar 27 04:33 Videos
drwxr-xr-x. 3 wulei wulei  182 Mar 30 19:37 vmtools

[wulei@obj02 ~]$ for i in $(ls);do echo item:  $i; done;
item: 1.txt
item: argsnum.sh
item: copy.sh
item: Desktop
item: Documents
item: Downloads
item: Music
item: notes
item: Pictures
item: Public
item: selfname.sh
item: show0.sh
item: show1.sh
item: Templates
item: th3perlin.sh
item: Videos
item: vmtools
[wulei@obj02 ~]$ 

8、while循环

[wulei@obj02 ~]$ sudo sh whiletest.sh 
The counter is 0
The counter is 1
The counter is 2
The counter is 3
The counter is 4
The counter is 5
The counter is 6
The counter is 7
The counter is 8
The counter is 9

[wulei@obj02 ~]$ cat whiletest.sh 
#!/bin/bash
COUNTER=0
while [ $COUNTER -lt 10 ]; do
echo The counter is $COUNTER
let COUNTER=COUNTER+1
done

9、until循环

[wulei@obj02 ~]$ sudo sh untiltest.sh 
COUNTER 20
COUNTER 19
COUNTER 18
COUNTER 17
COUNTER 16
COUNTER 15
COUNTER 14
COUNTER 13
COUNTER 12
COUNTER 11
COUNTER 10

[wulei@obj02 ~]$ cat untiltest.sh     
#!/bin/bash
COUNTER=20
until [ $COUNTER -lt 10 ]; do
echo COUNTER $COUNTER
let COUNTER-=1
done
[wulei@obj02 ~]$ 

10、拼接字符串

[wulei@obj02 ~]$ v1="hello";v2="world";v3=${v1}${v2};echo $v3
helloworld

11、函数相加

[wulei@obj02 ~]$ v1=1;v2=2;let v3=v1+v2;echo $v3
3

[wulei@obj02 ~]$ a=5;b=6;echo $(($a+$b))
11

[wulei@obj02 ~]$ a=5;b=6;echo $[$a+$b]
11

[wulei@obj02 ~]$ a=5;b=6;expr $a + $b
11

[wulei@obj02 ~]$ a=5;b=6;echo $a + $b|bc
11

[wulei@obj02 ~]$ a=5;b=6;awk 'BEGIN{print '"$a"'+'"$b"'}'
11

12、判断某个文件存在

[wulei@obj02 ~]$ ls
1.txt       Desktop    filedetect.sh  notes     selfname.sh  Templates     Videos
argsnum.sh  Documents  funcdemo.sh    Pictures  show0.sh     th3perlin.sh  vmtools
copy.sh     Downloads  Music          Public    show1.sh     untiltest.sh  whiletest.sh


#执行
[wulei@obj02 ~]$ sudo sh filedetect.sh 1.txt 
1.txt File exists
[wulei@obj02 ~]$ sudo sh filedetect.sh 2.txt 
2.txt File not exists


#源码
[wulei@obj02 ~]$ cat filedetect.sh 
#!/bin/bash
if [ -f $1 ]
then
echo "$1 File exists"
else
echo "$1 File not exists"
fi


13、获得文本的第10行 

#获得文本前10行
[wulei@obj02 ~]$ head -10 1.txt
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin

#管道重定向给tail取最后一行
[wulei@obj02 ~]$ 
[wulei@obj02 ~]$ 
[wulei@obj02 ~]$ 
[wulei@obj02 ~]$ head -10 1.txt |tail -1
operator:x:11:0:operator:/root:/sbin/nologin

14、 管道与bc预算

[wulei@obj02 ~]$ echo "scale=2; 10 / 3" |bc   
3.33

#!/bin/bash
#表示 10/3, 保留2位小数,将结果赋值给了num, 输出3.33
num=$(echo "scale=2; 10 / 3" | bc)
echo $num

15、检查命令是否执行成功,0代表成功,非0都是执行失败。

[nailwl@nailwl ~]$ ^C
[nailwl@nailwl ~]$ echo $?
130
[nailwl@nailwl ~]$ echo $#
0
[nailwl@nailwl ~]$ echo $?
0

16、传参检查


[nailwl@nailwl ~]$ sh ifcmd.sh 55 66
2
[nailwl@nailwl ~]$ cat ifcmd.sh 
#!/bin/bash

echo $#
exit

17、定期备份日志

#!/bin/bash
# 每周五三时三十分使用 tar 命令备份/var/log 下的所有日志文件
# vim /root/bin/backuplog.sh
# 编写备份脚本,备份后的文件名包含日期标签,防止后面的备份将前面的备份数据覆盖
# 注意 date 命令需要使用反引号括起来,反引号在键盘<tab>键上面
tar -czf log-`date +%Y%m%d`.tar.gz /var/log 

# 说明:
# -c 建立新的压缩文件
# -z 支持gzip解压文件
# -f (必选参数)使用档案名字,切记,这个参数是最后一个参数,后面只能接档案名。
# -v (可选)显示执行过程,这里临时计划,无需显示过程。

总结:
*.tar              用tar –xvf 解压
*.gz               用gzip -d或者gunzip 解压
*.tar.gz和*.tgz    用tar –xzf 解压
*.bz2              用bzip2 -d或者用bunzip2 解压
*.tar.bz2          用tar –xjf 解压
*.Z                用uncompress 解压
*.tar.Z            用tar –xZf 解压
*.rar              用unrar e解压
*.zip              用unzip 解压
# 编写计划任务,执行备份脚本。
[root@obj02 ~]# crontab -e
crontab: no changes made to crontab


#其中crontab 的内容如下:
30 3 * * 5 /root/bin/backuplog.sh


以下是 crontab 文件的格式:

{minute} {hour} {day-of-month} {month} {day-of-week} {full-path-to-shell-script} 

minute:        区间为0 – 59
hour:          区间为0 – 23
day-of-month:  区间为0 – 31
month:         区间为1 – 12
Day-of-week:   区间为0 – 7


以下是 crontab 的有效选项:

crontab –e :   修改 crontab 文件。
crontab –l :   显示 crontab 文件。 
crontab -r :   删除 crontab 文件。
crontab -ir:   删除 crontab 文件前提醒用户。

制定计划最重要的是对表,CST:中国标准时间 

知识点:

       1、date是系统时间,也叫软件时间。

       2、hwclock是BIOS时间,也叫硬件时间。

       3、系统时间与time.windows.com时间服务器同步:ntpdate time.windows.com

       4、BIOS时间与系统时间同步:sudo hwclock -w

18、一键安装LAMP

[root@obj02 ~]# cat /tmp/onekeyLNMP.sh 

#!/bin/bash
yum -y install httpd
yum -y install mariadb mariadb-devel mariadb-server
yum -y install php  php-mysql
if [ $? -eq 0 ];then
        systemctl start httpd mariadb
        systemctl enable httpd mariadb
fi 

这里安装Apache可能无法启动,80端口被占用,可能安装了tomcat或者是nginx 

检查端口被占用命令:

# Socket Statistics优势在于它能够显示更多更详细的有关TCP和连接状态的信息,比netstat更快速更高效。
ss -lntpd | grep :80

-l:  listening 【ss -l列出所有打开的网络连接端口】
-n:  numeric   【不解析服务名称】
-t: tcp
-p:  progress
-d,  dccp      【display only DCCP sockets】
-a:  all
-s:  summary   【显示 Sockets 摘要】
-r:  resolve   【解析服务名称】
-m:  memory    【显示内存情况】

netstat -lntpd | grep :80

lsof -i tcp:80
[root@obj02 ~]# cat /etc/httpd/conf/httpd.conf


......

#Listen 12.34.56.78:80
Listen 8080

......


我一般使用 / 在vim中进行搜索 "Linsten" 关键字。


检查命令
[root@obj02 ~]# systemctl start httpd.service
[root@obj02 ~]# systemctl enable httpd.service
[root@obj02 ~]# systemctl status httpd.service

19、监听内存及磁盘容量发告警邮件

#!/bin/bash
disk_size=$(df / | awk '/\//{print $4}')
mem_size=$(free | awk '/Mem/{print $4}')
while :
do
sleep 60
if  [ $disk_size -le 51200000 -a $mem_size -le 102400000 ]
then
    mail ‐s "Warning" root << EOF
        Insufficient resources,资源不足
EOF

    :<<COMMENTBLOCK
        这里是不会被执行的
        代码
        块
        儿
        用来注释整段脚本代码。 
        : 是shell中的空语句。
     COMMENTBLOCK

     touch /tmp/`date +%Y%m%d%H%M%S`.txt
fi
done



%H : 小时(00..23)
%M : 分钟(00..59)
%S : 秒(00..61)
%d : 日 (01..31)
%m : 月份 (01..12)
%Y : 完整年份 (0000..9999)

20、发邮件

# 邮件协议
POP3    Post Office Protocol - Version 3
IMAP    Internet Mail Access Protocol
SMTP    Simple Mail Transport Protocol

IMAP和POP有什么区别?
       POP允许电子邮件客户端下载服务器上的邮件,但是您在电子邮件客户端的操作(如:移动邮件、标记已读等),这是不会反馈到服务器上的。
       比如:您通过电子邮件客户端收取了QQ邮箱中的3封邮件并移动到了其他文件夹,这些移动动作是不会反馈到服务器上的。
也就是说,QQ邮箱服务器上的这些邮件是没有同时被移动的。

       IMAP就不同了,电子邮件客户端的操作都会反馈到服务器上,您对邮件进行的操作(如:移动邮件、标记已读等),服务器上的邮件也会做相应的动作。也就是说,IMAP是“双向”的。
       同时,IMAP可以只下载邮件的主题,只有当您真正需要的时候,才会下载邮件的所有内容。

 准备工作关闭其他mail软件

# 关闭centos自带的postifx
[root@obj02 ~]# systemctl stop postfix

[root@obj02 ~]# chkconfig postfix off
Note: Forwarding request to 'systemctl disable postfix.service'.


# 关闭安装的sendmail
[root@obj02 ~]# systemctl stop sendmail.service 

[root@obj02 ~]# chkconfig sendmail off
Note: Forwarding request to 'systemctl disable sendmail.service'.
Removed symlink /etc/systemd/system/multi-user.target.wants/sendmail.service.
Removed symlink /etc/systemd/system/multi-user.target.wants/sm-client.service.

配置mail.rc文件,在文件最底部追加如下内容:

vim /etc/mail.rc

# mail config
set [email protected]              #对方收到邮件时显示的发件人
set smtp=smtps://smtp.qq.com:465        #smtp服务器地址
set [email protected]    #用户名
set smtp-auth-password=xxxxxxxxxxxxxxxx #配置授权码,而不是邮箱的独立密码。
set smtp-auth=login                     #SMTP的认证方式,默认是login
set ssl-verify=ignore                   #SSL验证信息忽略
set nss-config-dir=/root/.certs         #证书所在目录,这个可以自定义目录所在位置

  QQ请求数字证书,这个费劲了,画个重点!

[root@obj02 .certs]# echo -n | openssl s_client -connect smtp.qq.com:465 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ~/.certs/qq.crt
depth=2 C = BE, O = GlobalSign nv-sa, OU = Root CA, CN = GlobalSign Root CA
verify return:1
depth=1 C = BE, O = GlobalSign nv-sa, CN = GlobalSign Organization Validation CA - SHA256 - G2
verify return:1
depth=0 C = CN, ST = guangdong, L = shenzhen, O = Tencent Technology (Shenzhen) Company Limited, CN = *.mail.qq.com
verify return:1
DONE
[root@obj02 .certs]# certutil -A -n "GeoTrust SSL CA" -t "C,," -d ~/.certs -i ~/.certs/qq.crt
[root@obj02 .certs]# certutil -A -n "GeoTrust Global CA" -t "C,," -d ~/.certs -i ~/.certs/qq.crt
[root@obj02 .certs]# certutil -A -n "GeoTrust SSL CA - G3" -t "Pu,Pu,Pu" -d ~/.certs/./ -i qq.crt
Notice: Trust flag u is set automatically if the private key is present.
[root@obj02 .certs]# certutil -L -d /root/.certs

Certificate Nickname                                         Trust Attributes
                                                             SSL,S/MIME,JAR/XPI

GeoTrust SSL CA                                              P,P,P
[root@obj02 .certs]# 

国际惯例,一定要测试看结果的:

echo "Mail Content Best Regards" | mail -s "Mail Subject" [email protected]

特别鸣谢:https://blog.csdn.net/qq_39626154/article/details/81706915

21、猜数字游戏

# 脚本生成一个 100 以内的随机数,提示用户猜数字。
# 根据用户的输入,提示用户猜对了猜小了或猜大了,直至用户猜对脚本结束。
# RANDOM 为系统自带的系统变量,值为 0‐32767的随机数
# 使用取余算法将随机数变为 1‐100 的随机数

num=$[RANDOM%100+1]
flag=true
echo "$num"


# 使用 read 提示用户猜数字
# 使用 if 判断用户猜数字的大小关系:
# ‐eq(等于) ‐ne(不等于)
# ‐gt(大于) ‐ge(大于等于)
# ‐lt(小于) ‐le(小于等于)

while  :
do
        read -p "计算机生成了一个 1‐100的随机数,你猜:" cai

        # 判断是否为合法输入
        while $flag
        do
                expr $cai + 0 &>/dev/null
                [ $? -eq 0 ] && flag=false || read -p "请输入一个 1‐100的整数 ☺ " cai
        done

        # 判断猜大猜小
        if [ $cai -eq $num ]
        then
                echo "恭喜,猜对了"
                exit
        elif [ $cai -gt $num ]
        then
                flag=true
                echo "Oops,猜大了"
        else
                flag=true
                echo "Oops,猜小了"
        fi
done

 22、校验权限自动部署vsftp

#!/bin/bash
if [ $USER == "root" ]
then
	yum ‐y install vsftpd
else
    echo "您不是管理员,没有权限安装软件"
fi

23、添加用户

#!/bin/bash
# 编写脚本:提示用户输入用户名和密码,脚本自动创建相应的账户及配置密码。如果用户
# 不输入账户名,则提示必须输入账户名并退出脚本;如果用户不输入密码,则统一使用默
# 认的 123456 作为默认密码。
 
read -p "请输入用户名: " user

# 使用‐z 可以判断一个变量是否为空,如果为空,提示用户必须输入账户名,并退出脚本,退出码为 2
# 没有输入用户名脚本退出后,使用$?查看的返回码为 2
if [ -z $user ];then
        echo "用户名不可为空"
        exit 2
fi


#使用 stty -echo 关闭 shell 的回显功能
stty -echo
read -p "请输入密码: " pass

#使用 stty  echo 打开 shell 的回显功能
stty echo

pass=${pass:-123456}

useradd "$user"

echo "$pass" | passwd --stdin "$user"

24、输入三个数并进行升序排序

#!/bin/bash

echo "三个整数升序排列程序"

# 用户输入三个整数
read -p "请输入第一个整数:" num1
read -p "请输入第二个整数:" num2
read -p "请输入第三个整数:" num3

# 定义临时中转变量
tmp=0

# 如果 num1 大于 num2,就把 num1 和和 num2 的值对调,确保 num1 变量中存的是最小值
if [ $num1 -gt $num2 ];then
        $tmp=$num2
        $num2=$num1
        $num1=$tmp
fi

# 如果 num1 大于 num3,就把 num1 和 num3 对调,确保 num1 变量中存的是最小值
if [ $num1 -gt $num3 ];then
        tmp=$num1
        num1=$num3
        num3=$tmp
fi

# 如果 num2 大于 num3,就把 num2 和 num3 对标,确保 num2 变量中存的是小一点的值
if [ $num2 -gt $num3 ];then
        tmp=$num2
        num2=$num3
        num3=$tmp
fi

echo -e "排序后数据(从小到大)为:$num1,$num2,$num3"

25、剪刀石头布

#!/bin/bash
# 编写脚本,实现人机<石头,剪刀,布>游戏

# 变量初始化
flag=true
game=(石头 剪刀 布)
p_score=0
c_score=0
playtimes=0
result=""

# 通过随机数获取计算机的出拳
# 出拳的可能性保存在一个数组中,game[0],game[1],game[2]分别是 3 中不同的可能

while $flag
do
	echo "请根据下列提示选择您的出拳手势"
	echo "1.石头"
	echo "2.剪刀"
	echo "3.布"
	echo "4.退出游戏"

    # 计算机随机出拳
    computer=${game[RANDOM%3]}

    # 游戏回合数+1
    let playtimes++

    read -p "请选择输入数字1‐3:" person

    case  $person  in
    # 玩家出石头
    1)
            if [ $computer = "石头" ];then
                    result="平局"
            elif [ $computer = "剪刀" ];then
                    result="玩家胜"
                    let p_score++
            else
                    result="计算机胜"
                    let c_score++
            fi

            echo "玩家:${game[person-1]},计算机:$computer。本次结果:$result"
            ;;
    # 玩家出剪刀
    2)   
            if [ $computer = "石头" ];then
                    result="计算机赢"
                    let c_score++
            elif [ $computer = "剪刀" ];then
                    result="平局"
            else
                    result="玩家赢"
                    let p_score++
            fi

            echo "玩家:${game[person-1]},计算机:$computer。本次结果:$result"
            ;;
    # 玩家出布
    3)
            if [ $computer = "石头" ];then
                    result="玩家赢"
                    let p_score++
            elif [ $computer = "剪刀" ];then
                    result="计算机赢"
                    let c_score++
            else
                    result="平局"
            fi

            echo "玩家:${game[person-1]},计算机:$computer。本次结果:$result"
            ;;
    # 玩家退出游戏
    4)
            echo "欢迎再玩"
            flag=false

            # 本次游戏无效不计入比赛成绩
            let playtimes--
            ;;
    # 玩家输入错误
    *)
            echo "必须输入 1‐3 的数字"

            # 本次游戏无效不计入比赛成绩
            let playtimes--
    esac

done

echo -e "总回合数:$playtimes,其中:胜$p_score,平$(( $playtimes-$p_score-$c_score )),败$c_score。"

特别鸣谢:

各种括号的说明:https://www.cnblogs.com/faberbeta/p/linuxshell040.html

各种运算符的说明:https://www.runoob.com/linux/linux-shell-basic-operators.html

26、主机状态扫描 

1、脚本代买如下

#!/bin/bash
# 编写脚本测试10.199.118.0/24 整个网段中
# 哪些主机处于开机状态,哪些主机处于关机状态

#定义一个函数,ping 某一台主机,并检测主机的存活状态
myping(){
        ping -c 2 -i 0.5 -W 10 $1 &>/dev/null
        if  [ $? -eq 0 ];then
                echo "$1 is up"
        else
                echo "$1 is down"
        fi
}

for i in {1..254}
do
        myping 10.199.118.$i &
done

# 使用&符号,将执行的函数放入后台执行
# 这样做的好处是不需要等待ping第一台主机的回应
# 就可以继续并发ping第二台主机

# 以下是for 版的实现,注释掉不会执行。
:<<NOTES
for i in {1..254}
do
    # 每隔0.3秒ping一次,一共ping2次,并以1毫秒为单位设置ping的超时时间
    ping -c 2 ‐i 0.5 ‐W 10 10.199.118.$i &>/dev/null
    if  [ $? -eq 0 ];then
        echo "10.199.118.$i is up"
    else
        echo "10.199.118.$i is down"
    fi
done
NOTES

# 以下是while版的实现,注释掉不会执行。
:<<NOTES
i=1
while [ $i -le 254 ]
do
   	ping ‐c 2 ‐i 0.3 ‐W 1 192.168.4.$i  &>/dev/null
   	if  [ $? -eq 0 ];then
       	echo "192.168.4.$i is up"
    else
       	echo  "192.168.4.$i is down"
   	fi
   	let i++
done
NOTES

2、执行并将结果导入IPstatus.txt
[root@obj02 bin]# chmod u+x scanlan.sh
[root@obj02 bin]# sh scanlan.sh > IPstatus.txt

3、查看结果并分析
[root@obj02 bin]# tail -50 IPstatus.txt |grep down
10.199.118.6 is down
10.199.118.7 is down
10.199.118.8 is down
10.199.118.9 is down
10.199.118.10 is down
10.199.118.12 is down
10.199.118.13 is down
10.199.118.14 is down

[root@obj02 bin]# tail -50 IPstatus.txt |grep up
10.199.118.11 is up
10.199.118.15 is up
10.199.118.16 is up
10.199.118.17 is up
10.199.118.19 is up
10.199.118.20 is up
10.199.118.21 is up

命令执行时间过长,强制中断 

4、强行关闭,命令时间太无法结束,重开一个SSH窗口。
[wulei@obj02 ~]$ ps -aux |grep ping 
gdm       2376  0.0  0.0 380612  3108 ?        Sl   01:37   0:00 /usr/libexec/gsd-housekeeping
root     18366  0.0  0.0 128452  1268 pts/0    S+   19:30   0:00 ping -c 2 -i 0.5 -W 100 10.199.118.36
wulei    18376  0.0  0.0 112716   960 pts/1    S+   19:31   0:00 grep --color=auto ping

[wulei@obj02 ~]$ sudo kill -9 18366
[sudo] password for wulei: 
[wulei@obj02 ~]$ 

5、kill进程无效,直接kill pts
[wulei@obj02 ~]$ ps -aux |grep ping 
gdm       2376  0.0  0.0 380612  3108 ?        Sl   01:37   0:00 /usr/libexec/gsd-housekeeping
root     18394  0.0  0.0 128452  1272 pts/0    S+   19:32   0:00 ping -c 2 -i 0.5 -W 100 10.199.118.38
wulei    18396  0.0  0.0 112716   960 pts/1    S+   19:32   0:00 grep --color=auto ping

[wulei@obj02 ~]$ sudo pkill -kill -t pts/0

[wulei@obj02 ~]$ ps -aux |grep ping       
gdm       2376  0.0  0.0 380612  3108 ?        Sl   01:37   0:00 /usr/libexec/gsd-housekeeping
wulei    18442  0.0  0.0 112716   960 pts/1    S+   19:34   0:00 grep --color=auto ping

27、九九表

#!/bin/bash

# 9*9 乘法表(编写 shell 脚本,打印 9*9 乘法表)

for i in `seq 9`
do
        for j in `seq $i`
        do
                echo -n "$j*$i=$[i*j]  "
        done

        echo
done

28、监控网卡ens160手法数据 

#!/bin/bash
# 使用死循环实时显示 eth0 网卡发送的数据包流量
while :
do
        echo  '本地网卡 ens160 流量信息如下: '
        ifconfig ens160 | grep "RX pack" | awk '{print $5 $6}'
        ifconfig ens160 | grep "TX pack" | awk '{print $5 $6}'
        echo
        sleep 5
done
~                                        

29、批量添加用户(默认密码)

1、代码

#!/bin/bash
# 使用 user.txt 文件中的人员名单,在计算机中自动创建对应的账户并配置初始密码
# 本脚本执行,需要提前准备一个 user.txt 文件,该文件中包含有若干用户名信息
for i in `cat user.txt`
do
   	useradd $i
   	echo "123456" | passwd ‐‐stdin $i
done


2、user.txt文件内容

Robbins
Lucy
Norton
EPSON
zhaichangquan
wangyunde
menhaitao
lihaotian

useradd命令详解 

创建用户好比买车,要考虑的配置:
    1、用户名
    2、密码
    3、UID
    4、用户组
    5、家目录
    6、登录到的shell
    7、sudo权限


命令格式:
    useradd [-d home] [-s shell] [-c comment] [-m [-k template]] [-f inactive] [-e expire ] [-p passwd] [-r] name


示例:
    useradd username
    等价于
    useradd username -g username -d /home/username -s /bin/bash


主要参数:
  -g:指定用户所属的群组。值可以使组名也可以是GID。用户组必须已经存在的,期默认值为100,即users。

  -d:指定用户登入时的主目录,替换系统默认值/home/<用户名>
  -m:自动建立用户的登入目录。

  -s:指定用户登入后所使用的shell。默认值为/bin/bash。

  -u:指定用户ID号。该值在系统中必须是唯一的。0~499默认是保留给系统用户账号使用的,所以该值必须大于499。

  -G:指定用户所属的附加群组。
  -M:不要自动建立用户的登入目录。
  -n:取消建立以用户名称为名的群组。

  -c:加上备注文字,备注文字保存在passwd的备注栏中。
  -D:变更预设值。
  -e:指定账号的失效日期,日期格式为MM/DD/YY,例如06/30/12。缺省表示永久有效。
  -f:指定在密码过期后多少天即关闭该账号。如果为0账号立即被停用;如果为-1则账号一直可用。默认值为-1.
  -r:建立系统账号。


useradd -u 544 -d /usr/testuser1 -g users -m testuser1
# 新建账户testuser1,UID为544,主目录为/usr/testuser1,属于users组:


adduser tmp_3452
passwd tmp_3452
# 添加用户并设置密码


useradd oracle -g oinstall -G dba
# 新建一个oracle用户,初始属于oinstall组,同时也属于dba组。


useradd tomcat -d /var/servlet/service -s /sbin/nologin
# 无法使用shell,指定用户目录为 /var/servlet/service

 30、批量添加用户(带密码)

username.txt的内容如下
stu1
stu2
stu3
stu4
stu5
stu6

serc.txt的内容如下
stu1:tt1
stu2:tt2
stu3:tt3
stu4:tt4
stu5:tt5
stu6:tt6


addpwdusers.sh代码如下

#!/bin/bash
#添加用户,并且在/home/ 下为用户生成用户目录。
cat < username.txt | xargs -n 1 useradd -m

#批处理模式下更新密码
chpasswd < serc.txt

#将上述的密码转换到密码文件和组文件
pwconv

#结束验证信息
echo "OK 新建完成"


执行该脚本文件,查看执行过程
[root@obj02 bin]# chmod u+x addpwdusers.sh
[root@obj02 bin]# sh addpwdusers.sh
OK 新建完成


在执行没有出错的情况下,不会输出任何的信息,不会与用户交互。
但是用户必须要记住那些设置项目,否则添加的用户可能出现一些预想不到的结果。

特别鸣谢:https://www.cnblogs.com/irisrain/p/4324593.html

 

其他参考资料:

https://blog.51cto.com/zero01/2046242

https://www.jb51.net/article/135168.htm

https://blog.csdn.net/yugemengjing/article/details/82469785

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章