zoukankan      html  css  js  c++  java
  • Linux之shell典型应用之脚本实现

    一、 提取Linux操作系统信息

    二、 获取操作系统运行状态

    三、 分析应用状态

    四、 应用日志分析

    第一章:VIM编辑器设置

    一、语法高亮

        syntax on/off

    二、显示行号

    set number

    set nonumber关闭行号

    三、自动缩近

    set autoindent

    set cindent

    四、自动加入文件头

    autocmd 即“自动命令”,在发生某些事件时自动执行,类似于钩子函数。

    BufNewFile 表示编辑一个新的文件

    脚本内容如下:

    autocmd BufNewFile *.sh, exec ":call SetTitle()"

    let $author_name = "zm"

    let $author_email="xxxxxx@163.com"

     

    func SetTitle()

    if &filetype == 'sh'

    call setline(1,"##################################################")

    call append(line("."),"# File Name:".expand("%"))

    call append(line(".")+1,"# Author:".$author_name)

    call append(line(".")+2,"# mail:".$author_email)

    call append(line(".")+3,"# Created Time:".strftime("%c"))

    call append(line(".")+4,"#===================================")

    call append(line(".")+5,"#!/bin/bash")

    call append(line(".")+6,"")

    else

    call setline(1,"##################################################")

    call append(line("."),"# File Name:".expand("%"))

    call append(line(".")+1,"# Author:".$author_name)

    call append(line(".")+2,"# mail:".$author_email)

    call append(line(".")+3,"# Created Time:".strftime("%c"))

    call append(line(".")+4,"#===================================")

    call append(line(".")+5,"#!/usr/bin/python")

    call append(line(".")+6,"")

    endif

    autocmd BufNewFile * normal G        #自动将光标定位到末尾

    endfunc

     

    第二章:Shell高亮显示

    基本格式:echo -e 终端颜色 + 显示内容 + 结束后的颜色

    例如:echo -e "e[1;30m Who am I ~ e[1;35m"

    1. echo -e 表示改变终端颜色

    2. "e[输出内容的颜色 输出内容 e输出结束后的颜色"

    3. [1;30m 中,1表示开启颜色,30m是颜色参数

    4. $(tput sgr0)表示回到终端默认的初始颜色

    一、场景脚本结构

     

    二、monitor_man.sh的实现

    扩展知识:Shell中的关联数组

    普通数组:只能使用整数索引

    关联数组:可以使用字符串作为数组索引

    declare -A ass_array1           #申明关联数组变量

    ass_array1[index1]=pear         #使用关联数组

     

    脚本内容如下:

    #!/bin/bash

    #

    resettem=$(tput sgr0)

    declare -A ssharray

    i=0

    numbers=””

    for script_file in ‘ls -I “monitor_man.sh” ./’

    do

           echo -e "e[1;35m" "The Script:" ${i} '==>' ${resettem} ${script_file}

           i=$ ((i+1))

    done

     

    脚本内容如下:

    #!/bin/bash

    resettem=$(tput sgr0)

    declare -A ssharray

    i=0

    numbers=""

    for script_file in `ls -I "monitor_man.sh" ./`

    do

            echo -e "e[1;35m" "The Script:" ${i} '==>' ${resettem} ${script_file}

    grep -E “^#Program function” ${script_file}       #打印功能注释

            ssharray[$i]=${script_file}

            numbers="${numbers} | ${i}"

            i=$ ((i+1))

    done

     

    while true

    do

            read -p "Please input a number [ ${numbers} ]:" execshell

            if [[ ! ${execshell} =~ ^[0-9]+ ]];then

            exit 0

            fi

            /bin/sh ./${ssharray[$execshell]}

    done

     

    第三章:系统信息及运行状态获取

    一、system_monitor.sh功能

    功能一、提取操作系统信息(内核、系统版本、网络地址等)

    功能二、分析系统的运行状态(CPU负载、内存及磁盘使用率等)

    二、system_monitor.sh的实现功能一

    #!/bin/bash

    #

    clear

    if [[ $# -eq 0 ]] ;then

    #Define Variable (定义变量)reset_terminal

    reset_terminal=$(tput sgr0)

    ##########################功能一###########################

    #检查系统类型

    os=$(uname -o)

    echo -e 'E[36m'"Operating System Type: " $reset_terminal $os

    #检查系统版本和名称

    #grep -e 指定字符串作为查找文件内容的范本样式

    os_name=$(cat /etc/issue | grep -e "Server")

    echo -e 'E[36m'"Check OS Release Version and Name: " $reset_terminal $os_name       

    #检查CPU体系结构

    architecture=$(uname -m)

    echo -e 'E[36m'"Check Architecture: " $reset_terminal $architecture

    #检查内核版本

    kernelrelease=$(uname -r)

    echo -e 'E[36m'"Check Kernel Release: " $reset_terminal $kernerrelease

    #检查主机名:echo $HOSTNAME

    hostname=$(uname -n)

    echo -e 'E[36m'"Check Hostname: " $reset_terminal $hostname

    #检查内网IP

    internalip=$(hostname -I)

    echo -e 'E[36m'"Check Internal IP: " $reset_terminal $internalip

    #检查公网IP(curl ifconfig.me)

    externalip=$(curl -s http://ipecho.net/plain)

    echo -e 'E[36m'"Check External IP: " $reset_terminal $externalip

    #检查DNS

    nameservers=$(cat /etc/resolv.conf | grep -E "<nameserver[ ]+" | awk '{print $NF}')

    echo -e 'E[36m'"Check DNS: " $reset_terminal $nameservers

    #检查网络状况

    ping -c 2 baidu.com &>/dev/null && echo "Internet:Connected" || echo "Internet:Disconnected"

    #检查用户登录

    who>/tmp/who

    echo -e 'E[36m' "Logged In Users" $reset_terminal && cat /tmp/who

    rm -f /tmp/who

    ##########################功能二###########################

    #操作系统内存使用

    system_mem_usages=$(awk '/MemTotal/{total=$2}/MemFree/{free=$2}END{print (total-free)/1024}' /proc/meminfo)

    #操作系统应用内存使用

    app_mem_usages=$(awk '/MemTotal/{total=$2}/MemFree/{free=$2}/^Cached/{cached=$2}/Buffers/{buffers=$2}END{print (total-free-cached-buffers)/1024}' /proc/meminfo)

            echo -e 'E[32m'"Operating System Memuserages :" $reset_terminal $system_mem_usages MB

            echo -e 'E[32m'"Operating System App Memuserages :" $reset_terminal $app_mem_usages MB

    #操作系统负载情况

    loadaverage=$( top -n 1 -b | grep "load average:" | awk '{print $12 $13 $14}')

            echo -e 'E[32m'"Operating System Load Averages :" $reset_terminal $loadaverage

    #操作系统磁盘容量使用情况

    diskaveage=$(df -hP | grep -vE 'Filesystem | tmpfs' | awk '{print $1 " " $5}')

     

            echo -e 'E[32m'"Operating System Disk Averages :" $reset_terminal $diskaveage

    fi

    三、扩展知识

    1. cat /proc/meminfo 目录下可以看系统监控信息

    2. awk执行中不能用echo,要用print

    3. awk中的变量数值可以直接计算,不需要加$(),而且计算准确到浮点型

    4. awk '/abc/{执行动作一}' 文件名: 指提取含有abc字符串的行,然后执行后面的动作

    5. 注意在/proc/meminfo下截取"cached"发现结果有两个,要注意筛选

    [root@localhost ~]# cat /proc/meminfo | grep -E "^Cached"

    Cached:           469732 kB

     

    第四章:ngnix和mysql应用状态分析

    一、check_server.sh的实现

    (1)监控nginx脚本

    #!/bin/bash

    Resettem=$(tput sgr0)

    #nginx地址赋予给变量

    Nginxserver='http://x.x.x.x/nginx_status'

    #Mysql从库ip地址赋予给变量

    Mysql_Slave_Server='从库IP地址'

    Mysql_User='从库用户名'

    Mysql_Pass='从库用户名密码'

     

    Check_Nginx_Server()

    {

    Status_Code=$(curl -m 5 -s -w %{http_code} ${Nginxserver} -o /dev/null)

    if [ $Status_Code -eq 000 -o $Status_Code -ge 500 ]

    then

    echo -e 'E[32m' "Check http server error! Response status code is" $Resettem $Status_code

    else

    Http_content=$(curl -s ${Nginxserver})

    echo -e 'E[32m' "Check http server ok! " $Resettem $Http_content

    fi

    }

     

    Check_Mysql_Server()

    {

    nc -z -w2 ${Mysql_Slave_Server} 3306 &>/dev/null

    echo -e 'E[32m'"The connnections to mysql server succeeded! " $Resettem

    if  [ $? -eq 0 ];then

    mysql -u${Mysql_User} -p${Mysql_Pass} -h${Mysql_Slave_Server} -e

    "show slave statusG" | grep "Slave_IO_Running" | awk '{if($2 !="Yes"){print "Slave thread not running!";exit 1}}'

    if [ $? -eq 0 ];then

    mysql -u${Mysql_User} -p${Mysql_Pass} -h${Mysql_Slave_Server} -e

    "show slave statusG" | grep "Seconds_Behind_Master"

    fi

    else

    echo "Connect Mysql Slave Server not succeeded"

    fi

    }

    Check_Nginx_Server

    Check_Mysql_Server

     

    (2)利用shell监控mysql

    1、搭建主从复制状态

    2、基于mysql客户端连接,获取主从复制状态

    mysql>show slave statusG;

                       Slave_IO_Running-IO线程是否有连接到主服务器上

                       Seconds_Behind_Master-主从同步的延时时间

     

     

    第五章:应用日志分析

    一、常见系统日志文件

    1、系统日志

    /var/log/messages   //系统主日志文件

    /var/log/secure     //认证、安全

    /var/log/dmesg    //和系统启动有关

    2、应用服务

    access.log         //nginx访问日志

    mysqld.log       //mysql运行日志

    xferlog         //和访问FTP服务器相关

    3、程序脚本

    开发语言:c、c++、java、php

    框架:Django、MVC、Servlet

    脚本语言:Shell、Python

    二、nginx的log_format介绍

    $remote_addr 是指IP,

    [$time_local]是当下时间,

    $request是指访问的URL,

    $status是状态,

    $body_bytes_send是发送客户端字节数,

    $Http_refer是指上一级页面的链接,

    $Http_user_agent是URL的头,

    $Http_x_forwarded_for是指真实的IP

    三、http状态码介绍

    1** 信息,服务器收到请求,需要请求者继续执行操作

    2** 成功,操作被成功接收并处理

    3** 重定向,需要进一步的操作以完成请求

    4** 客户端错误,请求包含语法错误或无法完成请求

    5** 服务器错误,服务器在处理请求的过程中发生了错误

    四、check_http.sh脚本的实现

    #!/bin/bash

    resettem=$(tput sgr0)

    Logfile_path=’/opt/logs/ngnix/access.log’

    Check_http_status()

    {

    Http_status_code=(`cat $Logfile_path | grep -ioE “HTTP/1.[1|0]”[[:blank]][0-9]{3}” | awk -F”[ ]+” ‘{

    if($2>100&&$2<200)

           {i++}

    else if($2>=200&&$2<300)

           {j++}

    else if($2>=300&&$2<400)

    {k++}

    else if($2>=400&&$2<500)

    {n++}

    else if($2>=500)

    {p++}

    }END{

    print i?i:0,j?j:0,k?k:0,n?n:0,p?p:0,i+j+k+n+p

    }’

    `)

    echo -e 'E[33m'"The number of http status [100+]:" ${resettem} ${ Http_status_code[0] }

    echo -e 'E[33m'"The number of http status [200+]:" ${resettem} ${ Http_status_code[1] }

    echo -e 'E[33m'"The number of http status [300+]:" ${resettem} ${ Http_status_code[2] }

    echo -e 'E[33m'"The number of http status [400+]:" ${resettem} ${ Http_status_code[3] }

    echo -e 'E[33m'"The number of http status [500+]:" ${resettem} ${ Http_status_code[4] }

    echo -e 'E[33m'"ALL request numbers:" ${resettem} ${ Http_status_code[5] }

    }

     

    Check_http_code()

    {

    Http_Code=(`cat $Logfile_path | grep -ioE “HTTP/1.[1|0]”[[:blank]][0-9]{3}” | awk -v total=0 -F '[ ]+''{

    if ($2!="")

                              {code[$2]++;total++}

    else

    {exit}

    }END{

                         print code[404]?code[404]:0,code[403]?code[403]:0,total

                         }'

                         `)

    echo -e 'E[33m'"The number of http status[404]:" ${resettem} ${Http_Code[0]

    }

    echo -e 'E[33m'"The number of http status[403]:" ${resettem} ${Http_Code[1]

    }

    echo -e 'E[33m'"All request number:" ${resettem} ${Http_Code[2]})

    }

     

    Check_http_status

    Check_http_code

  • 相关阅读:
    数据结构 trie 树 入门练手 POJ 3630 Phone List
    回溯法求 1~n 的排列
    POJ 1988 Cube Stacking (并查集,节点到根节点的距离题目)
    Ubuntu下的截图软件
    git使用方法
    在Linux下安装ADT
    在Linux下安装Android SDK
    在Linux下安装Java JDK
    研发项目风险因素差异性
    关于C#的partial修饰符
  • 原文地址:https://www.cnblogs.com/huhyoung/p/8331199.html
Copyright © 2011-2022 走看看