linux学习笔记-Shell(三):shell脚本的基础知识

一.什么是shell

脚本中命令的解释器

二.shell脚本的意义

1.记录命令执行的过程和执行逻辑,以便以后重复执行
2.脚本可以批量处理主机
3.脚本可以定时处理主机

三.如何创建shell脚本

#!/bin/bash    幻数
vim自动添加脚本首部
"map <F4> ms:call WESTOSTITLE()<cr>'s
autocmd BufNewFile *.sh,*.script call WESTOSTITLE()
func WESTOSTITLE()
 call append(0,"###############################################")
 call append(1,"# Author: lee")
 call append(2,"# Version: ")
 call append(3,"# Create_Time: ".strftime("%Y/%m/%d"))
 call append(4,"# Mail: lee@westos.org")
 call append(5,"# Info: ")
 call append(6,"# ")
 call append(7,"################################################")
 call append(8,"")
 call append(9,"#!/bin/bash")
endfunc

在这里插入图片描述

四.如何执行shell脚本

1).手动在环境中开启指定解释器

sh script.sh

在这里插入图片描述

2).直接在当前环境中运行shell中的指令不开启新的shell

source script.sh
. script.sh

在这里插入图片描述
在这里插入图片描述

3).开启脚本中指定的shell并使用此shell环境运行脚本中的指令

chmod +x script.sh
/xxx/xxx/script.sh
./script.sh

在这里插入图片描述
在这里插入图片描述
4)指定自动寻找使用bash
在这里插入图片描述

五.如何对脚本进行调试

sh -x /mnt/westos.sh
+        运行指令
不带+    命令运行的输出

在这里插入图片描述

脚本练习:
1
ip_show.sh 网卡 显示当前的IP
在这里插入图片描述

2
host_messages.sh 显示当前主机的名称,ip登陆当前主机的用户
hostname: xxxxx
ipaddress: xxxx.xxxx.xxx.xxx
username: root

echo hostname:$(hostname)
echo ipaddress:$(ifconfig ens3|awk '/inet\>/{print $2}')
echo username:$(whoami)

3.clear_log.sh 执行次脚本后可以清空日志

> /var/log/messages &> &&{
echo clrear all
}

4.统计访问当前主机次数最多的ip及次数
统计最多访问ip

#!/bin/bash
[ "$USER" != "root" ] && {
         echo please run in root
         exit
}
 IP=$(awk '{print $1}' $1 |sort -n|uniq -c |sort -t " " -k 2 -rn| head -n 1 |sed -n 1p | awk '{print $2}')
 count=$(awk '{print $1}' $1 |sort -n|uniq -c |sort -t " " -k 2 -rn| head -n 1 |sed -n 1p | awk '{print $1}')
  echo -e "the most ip is :" "$IP" 
   echo -e "count is :" "$count" 

5.创建user文件: user1 user2 user3
passwd: 123 456 789
创建脚本自动读取文件内容并创建用户及默认密码

[ -z "$1" ] && {
            echo please input userlist file folling script
            exit
}
[ -z "$2" ] && {
            echo please input passlist file folling script
            exit
}
[ -e "$1"  ] && {
         [ -f "$1" ]  || {
            echo -e  "$1 is not userlist file"
            exit
             }
}  || {
            echo -e "$1 is not exist"
            exit
}

[ -e "$2"  ] && {
         [ -f "$2" ]  || {
            echo -e  "$2 is not userlist file"
            exit
             }
}  || {
            echo -e "$2 is not exist"
            exit
}


m=1
for USERNAME in $(cat $1)
do
    useradd  $USERNAME  && echo -e "$USERNAME is created "

    PASSWD=$(sed -n $m\p $2)
    echo     $PASSWD      | passwd --stdin $USERNAME && echo -e "$USERNAME passwd is $PASSWD 注:测试用,工作情况禁止输出密码!!!" 
    let m++
    echo
    echo
done

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值