一、 提取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! \n" $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! \n" $Resettem

if  [ $? -eq 0 ];then

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

"show slave status\G" | 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 status\G" | 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 status\G;

                   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

Linux之shell典型应用之脚本实现的更多相关文章

  1. Linux - 简明Shell编程11 - 调用脚本(CallTheScript)

    脚本地址 https://github.com/anliven/L-Shell/tree/master/Shell-Basics 示例脚本及注释 主脚本: CallTheScript.sh #!/bi ...

  2. 一起来学linux:shell script(二)关于脚本

    (一)首先来看shell脚本的执行方式,shell脚本的后缀名都是sh文件. 1 sh test.sh 2 source test.sh 这两种方式有什么区别呢.test.sh 里的脚本很简单, 从键 ...

  3. Linux添加shell(.sh)脚本并添加定时任务

    一.添加sheel脚本 1.首先创建一个执行程序:vim a.sh 2.编辑: #!/bin/bash  python3  python.py >> test2.log 2>& ...

  4. Linux 的shell 字符串截取很有用。有八种方法。

    一 Linux 的字符串截取很有用.有八种方法. 假设有变量 var=http://www.linuxidc.com/123.htm 1  # 号截取,删除左边字符,保留右边字符. echo ${va ...

  5. 详解Linux交互式shell脚本中创建对话框实例教程_linux服务器

    本教程我们通过实现来讲讲Linux交互式shell脚本中创建各种各样对话框,对话框在Linux中可以友好的提示操作者,感兴趣的朋友可以参考学习一下. 当你在终端环境下安装新的软件时,你可以经常看到信息 ...

  6. 使用C#给Linux写Shell脚本(下篇)

    在上篇的<使用C#给Linux写Shell脚本>结尾中,我们留下了一个关于C#如何调用BashShell的问题.在文章发布之后,我留意到有读者留言推荐使用“Pash”(一款类PowerSh ...

  7. Linux/Unix shell 脚本中调用SQL,RMAN脚本

    Linux/Unix shell脚本中调用或执行SQL,RMAN 等为自动化作业以及多次反复执行提供了极大的便利,因此通过Linux/Unix shell来完成Oracle的相关工作,也是DBA必不可 ...

  8. Linux常用Shell脚本珍藏【转载】

    我们在运维中,尤其是linux运维,都知道脚本的重要性,脚本会让我们的 运维事半功倍,所以学会写脚本是我们每个linux运维必须学会的一门功课,这里收藏linux运维常用的脚本.如何学好脚本,最关键的 ...

  9. Linux系列教程(二十)——Linux的shell概述以及如何执行脚本

    从这篇博客开始,我们将进入Linux的shell脚本的学习,这对于Linux学习爱好者而言是特别重要的一节,也是特别有意思的一节,shell 脚本就像我们知道的Java,php类似的编程语言一样,通过 ...

随机推荐

  1. BZOJ 3238: [Ahoi2013]差异 [后缀自动机]

    3238: [Ahoi2013]差异 Time Limit: 20 Sec  Memory Limit: 512 MBSubmit: 2512  Solved: 1140[Submit][Status ...

  2. 使用xUnit为.net core程序进行单元测试(4)

    第1部分: http://www.cnblogs.com/cgzl/p/8283610.html 第2部分: http://www.cnblogs.com/cgzl/p/8287588.html 第3 ...

  3. gitlab wiki 500

    记录一次使用gitlab各种报500的问题,并怎么解决的描述下 一.问题背景 描述我第一次使用wiki的步骤: 二.问题描述 之后我进行任何合法的操作(创建页面使用全英文名称:页面不做任何修改,只是点 ...

  4. 携程Apollo(阿波罗)配置中心用户管理和部门管理

    Apollo是配置管理系统,会提供权限管理(Authorization),理论上是不负责用户登录认证功能的实现(Authentication).所以Apollo定义了一些SPI用来解耦,Apollo接 ...

  5. 使用CentOS Linux Bridge搭建Vxlan环境

    一. 基础环境使用VmWare虚拟两台Linux机器.CentOS 7,Linux内核如下:4.5.3-1.el7.elrepo.x86_64如果内核版本太低,是不支持VxLan的.可以使用一下命令进 ...

  6. 阿里云CentOS使用iptables禁止某IP访问

    在CentOS下封停IP,有封杀网段和封杀单个IP两种形式.一般来说,现在的攻击者不会使用一个网段的IP来攻击(太招摇了),IP一般都是散列的.于是下面就详细说明一下封杀单个IP的命令,和解封单个IP ...

  7. C++11 标准库也有坑(time-chrono)

    恰巧今天调试程序遇到时间戳问题, 于是又搜了搜关于取时间戳,以及时间戳转字符串的问题, 因为 time()   只能取到秒(win和linux) 想试试看能不能找到 至少可以取到毫秒的, 于是, 就找 ...

  8. CodeForces 820C

    题意略. 这道题目的出题者竟然被hack了!? 我的思路是:在游戏开始时,为了尽量少地用字母,我应该尽量选取计算机输出的前a个字母中已经使用过的字母.但是为了使电脑也尽量少用字母,我添加的这b个字母应 ...

  9. 用Eclipse Maven 创建 Web 3.0 项目问题 正确的处理步骤

    在Eclipse 安装好Maven插件后,创建Maven webapp项目,在工程 properties -> project facets 界面中将 Dynamic Web Module 修改 ...

  10. git 域名配置

    在Godaddy购买的域名: 查找DNSpod解析域名,没什么难度,就是添加一条记录,保存而已,记得在添加域名到DNSpod之后,复制两个NS地址到godaddy的域名服务器下: Git项目根目录下创 ...