shell-Batch Patrol Server script

Source: Internet
Author: User
Tags dmesg

Document description

The shell script is designed to provide a relatively automated solution for the patrol of a large number of Linux servers. The script consists of three parts: shellsh.sh, checksh.sh, file.txt; these three files need to be placed in a folder under the root permission to execute, indispensable.

Script usage

The IP address of the server to be patrolled and the corresponding password are all put in file.txt, each line of one IP corresponding to a password. Then run with the following command:

#./shellsh.sh file.txt192.168.182.143 123456

where file.txt can replace the file name, 192.168.182.143 the server to which you want to save the patrol log ip,123456 the server's password.

Run results

After running, the 192.168.182.143 server will be upgraded to a directory in the/tmp directory, that is: gatherlogdirectory This directory is stored in the patrol of the server's patrol log, these logs are patrolled by the server's IP name, Shape: 192.168.182.146.log. On the polling server will be upgraded to two directories namely: Checkscript, Localserverlogdirectory Where Checkscript is the checksh.sh script, and Localserverlogdirectory stores the log that was promoted after the checksh.sh was run on that server.

Test results

I only have three on the virtual machine tested on a Linux system, namely Ubuntu, RedHat, Kali. Running normally, the average patrol of a server takes 3 minutes.

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/7F/9A/wKioL1ckc5ez9P-OAAD0Oh7n88U932.png "title=" Eqwreqwr.png "alt=" Wkiol1ckc5ez9p-oaad0oh7n88u932.png "/>

Script code

Shellsh.sh:

#!/bin/bashlogin_info=$1gather_server_ip=$2gather_server_password=$3grep_ip= ' ifconfig | grep  ' \ ([[:d igit:]]\{1,3\}\.\) \{3\}[[:d igit:]]\{1,3\} '  --color=auto -o | sed -e  ' 2,5d ' Gatherpath= "/tmp/gatherlogdirectory" checkscriptpath= "/tmp/checkscript" IF&NBSP;[&NBSP;$#&NBSP;-NE&NBSP;3&NBSP;] ; then    echo -e  "parameters if fault!\n"      echo -e  "Please using:$0 login_info gather_server_ip\n"      echo -e  "for example: $0 ipandpassword.txt  $grep _ip\n"      exit;fiif [ ! -x  "$GatherPath"  ];then    mkdir  "$GatherPath"     echo -e  "The log ' s path is:  $GatherPath" ficat $ login_info | while read linedo    server_ip= ' echo  $line |awk  ' {print $1} ' &NBSp;   server_password= ' echo  $line |awk  ' {print $2} '     login _server_command= "ssh -o stricthostkeychecking=no [email protected] $server _ip"      scp_gather_server_checksh= "scp checksh.sh [email protected] $server _ip:$ Checkscriptpath "/usr/bin/expect<<eof        set timeout  20        spawn  $login _server_command         expect {                     "*yes/no"  { send  "yes\r";  exp_continue  }                     "*password:"  { send  "$server _password\r"  }                }    expect  "Permission denied, please try again ."  {exit}        expect  "#"  { send  "mkdir  $CheckScriptPath \ r "}        expect eof         exiteof/usr/bin/expect<<eof        set  timeout 20        spawn  $SCP _gather_server_checksh         expect {                     "*yes/no"  { send  "yes\r";  exp_continue }                     "*password:"  { send  "$server _password\r"  }                }expect  "Permission denied, please try  again. "  {exit}expect  "connection refused"  {exit}         expect  "100%"         expect eof         exitEOF    /usr/bin/expect<<EOF         set timeout 60        spawn $ login_server_command        expect {                     "*yes/no"  {  send  "Yes\r"; exp_continue }                     "*password:"  { send  "$server _password\r"  }               }    expect  "Permission denied, please try again."  {exit}        expect  "#"  { send  "cd $ Checkscriptpath;. /checksh.sh  $gather _server_ip  $gather _server_password\r "}         expect eof        exiteofdone

Checksh.sh

#!/bin/bash######################################################################################## #Function: # This script checks the system ' S information,disks ' s information,performance,etc. .. of the#server# #Author: #By  jack wang# #Company: #ShaanXi  great wall information  co.,ltd.################################################################################################ ################################################################################# #GatherServerIpAddress   Is the server ' s ip address that gather the checking log# Gatherserverpassword is the server ' s ip address that gather the  checking log######################################################################################### gatherserveripaddress=$1gatherserverpassword=$2############################################################### ######################### #Gettheipcommand is a command that you can get the ip address# ###################################################################################### #GetTheIpCommand = ' ifconfig | grep  ' \ ([[:d igit:]]\{1,3\}\.\] \{3\}[[:d igit:]]\{1,3\} '  --color=auto -o  | sed -e  ' 2,5d ' ######################################################################### ############### #LogName  is a command that your logs ' name######################## ############################################################### #LogName = ' ifconfig|grep  ' \ ([[:d igit:]]\{ 1,3\}\.\) \{3\}[[:d igit:]]\{1,3\} '  --color=auto -o|sed -e  ' 2,5d ' ' echo  '-"' date  +%y%m%d ' ########################################################################################## Gatherlogpath is a path that collecting log path#localserverlogpath is  local log path######################################################################################## #GatherServerLogPath = "/tmp /gatherlogdirectory "localserverlogpath="/tmp/localserverlogdirectory "######################################### ############################################### #LinuxOsInformation  is function that usege  to collect os ' s information############################################################## ######################### #LinuxOsInformation () {hostname= ' Hostname ' unamea= ' uname -a ' osversion= ' cat / etc/issue | sed  ' 2,4d ' uptime= ' uptime|awk  ' {print $3} ' |awk -f  ', '   ' { print $1} ' serverip= ' ifconfig|grep  "inet" |sed  ' 2,4d ' |awk -f  ': '   ' {print $2} ' |awk  ' {print $1} ' servernetmask= ' ifconfig|grep  ' inet ' |sed  ' 2,4d ' |awk -f  ': '   ' {print $4} ' |awk  ' {print $1} ' servergateway= ' netstat -r|grep  ' default ' |awk   ' {print $2} '' siglememorycapacity= ' dmidecode|grep -p -a5  "Memory\s+device" |grep  "Size" |grep -v   "Range" |grep  ' [0-9] ' |awk -f  ":"   ' {print $2} ' |sed  ' s/^[ \t]*//g ' Maximummemorycapacity= ' dmidecode -t 16|grep  "maximum capacity" |awk -F  ":"   " {print $2} ' |sed  ' s/^[ \t]*//g ' numberofmemoryslots= ' dmidecode -t 16|grep  ' number  of devices "|awk -f ": "  ' {print $2} ' |sed  ' s/^[ \t]*//g ' MemoryTotal= ' cat /proc/meminfo|grep  "Memtotal" |awk  ' {printf ("memtotal:%1.0fgb\n", $2/1024/1024)} ' |awk -F   ":"   ' {print $2} ' physicalmemorynumber= ' dmidecode|grep -a16  "Memory device" |grep   "Size:" |grep -v  "no module installed" |grep -v  "range size:" |wc - L ' productname= ' dmidecode|grep -a10  "system information" |grep  "Product Name" |awk  -f  ":"   ' {print $2} ' |sed  ' s/^[ \t]*//g ' systemcpuinfomation= ' cat /proc/cpuinfo|grep  ' name ' |cut   -d: -f2|awk  ' {print  ' * ' $1,$2,$3,$4} ' |uniq -c|sed  ' s/^[ \t]*//g ' echo  -e  "hostname| $Hostname \nunamea| $UnameA \nosversion| $OsVersion \nuptime| $Uptime \nserverip| $ServerIp \ nservernetmask| $ServerNetMask \nservergateway| $ServerGateWay \nsiglememorycapacity| $SigleMemoryCapacity \ nmaximummemorycapacity| $MaximumMemoryCapacity \nnumberofmemoryslots| $NumberOfMemorySlots \nmemorytotal|$ memorytotal\nphysicalmemorynumber| $PhysicalMemoryNumber \nproductname| $ProductName \nsystemcpuinformation|$ Systemcpuinfomation "}performanceinfomation  () {cpuidle= ' Top -d 2 -n 1 -b|grep  C[Pp][Uu]|grep id|awk  ' {print $5} ' |awk -f  '% '   ' {print $1} ' Cpuloadaverage= ' top -d 2 -n 1 -b|grep  "load average:" |awk -F  ":"   ' {print $5} ' |sed  ' s/^[ \t]*//G ' processnumbers= ' top -d 2 -n 1 -b|grep  "Tasks" |awk -f  "[:  ,]"   ' {print $3} ' processrunning= ' top -d 2 -n 1 -b|grep  ' Tasks ' |awk - f  "[:  ,]"   ' {print $8} ' processsleeping= ' Top -d 2 -n 1 -b|grep   "Tasks" |awk -f  "[:  ,]"   ' {print $11} ' processstoping= ' Top -d 2 -n  1 -b|grep  "Tasks" |awk -f  "[:  ,]"   ' {print $16} ' processzombie= ' top  -d 2 -n 1 -b|grep  "Tasks" |awk -f  "[:  ,]"   ' {print $21} ' ' userspacecpu= ' top -d 2 -n 1 -b|grep  ' c[pp][uu] ' |head -1|awk -f  ' [:  ,%] "  ' {print $4} ' systemspacecpu= ' top -d 2 -n 1 -b|grep  ' C[Pp] [Uu] ' |head -1|awk -f  ' [:  ,%] '   ' {print $8} ' changeprioritycpu= ' top -d 2  -n 1 -b|grep  ' c[pp][uu] ' |head -1|awk -f  ' [:  ,%] '   ' {print $12} ' WaitingCPU= ' top  -d 2 -n 1 -b|grep  ' c[pp][uu] ' |head -1|awk -f  "[:  ,%]"   ' {print $19} ' hardwareirqcpu= ' top -d 2 -n 1 -b|grep  ' C[Pp][Uu] ' |head - 1|awk -f  "[:  ,%]"   ' {print $23} ' softwareirqcpu= ' top -d 2 -n 1  -b|grep  ' c[pp][uu] ' |head -1|awk -f  ' [:  ,%] '   ' {print $27} ' memused= ' top -d 2 -n 1 -b|grep  "Mem" |awk -f  "[:  ,]"   ' {print $11} ' |tr -d  ' a-za-z "|awk  ' {printf ("%dm\n ", $1/1024)} ' memfreep= ' top -d 2 -n 1  -b|grep  "Mem" |awk -f  "[:  ,]"   ' {print $16} ' |tr -d  "A-za-z" |awk   ' {printf ("%dm\n", $1/1024)} ' membuffersp= '  top -d 2 -n 1 -b|grep  "Mem" |awk -f  "[: &NBSP;,] "  ' {print $22} ' |tr -d " a-za-z "|awk  ' {printf ("%dm\n ", $1/1024)} ' cachecachedp= ' top -d 2 -n 1 -b|grep  "Swap" |awk -f  "[:  ,]"   "{print $24 } ' |tr -d  ' a-za-z "|awk  ' {printf ("%dm\n ", $1/1024)} ' cachetotal= ' top -d 2 -n 1  -b|grep  "Swap" |awk -f  "[:  ,]"   ' {print $4} ' |tr -d  "A-za-z" |awk   ' {printf ("%dm\n", $1/1024)} ' cacheused= ' top -d 2 -n 1 -b|grep  "Swap" |awk  -F  "[:  ,]"   ' {print $14} ' |tr -d  "a-za-z" |awk  ' {printf ("%dm\n", $1/1024) } ' cachefree= ' top -d 2 -n 1 -b|grep  "Swap" |awk -f  "[:  ,] '   ' { print $18} ' |tr -d  ' a-za-z ' |awk  ' {printf ("%dm\n", $1/1024)} ' echo -e  ' CPUIdle|$ cpuidle\ncpuloadaverage| $CPUloadAverage \nprocessnumbers| $ProcessNumbers \nprocessrunning| $ProcessRunning \ Nprocesssleeping| $ProcessSlEeping\nprocessstoping| $ProcessStoping \nprocesszombie| $ProcessZombie \nuserspacecpu| $UserSpaceCPU \ nsystemspacecpu| $SystemSpaceCPU \nchangeprioritycpu| $ChangePriorityCPU \nwaitingcpu| $WaitingCPU \nhardwareirqcpu| $HardwareIRQCPU \nsoftwareirqcpu| $SoftwareIRQCPU \nmemused| $MemUsed \nmemfreep| $MemFreeP \nmembuffersp|$ membuffersp\ncachecachedp| $CacheCachedP \ncachetotal| $CacheTotal \ncacheused| $CacheUsed \ncachefree| $CacheFree \ n " }opratesystemsec  ()  {echo  ' ======================userlogin====================== ' wecho  ' = = ====================fileused======================= ' df -ahecho  ' ======================dmesgerror==== ================= ' dmesg | grep errorecho  ' ======================dmesgfail================= ===== ' dmesg | grep failecho  ' ======================bootlog======================== ' more  /var/log/boot.log | grep -V  "OK"  | sed  ' 1,6d ' echo  ' ============= =========route -n======================= ' route -necho  ' ======================iptables -l==================== ' iptables - lecho  ' ======================netstat -lntp================== ' netstat -lntpecho  ' ========== ============netstat -antp================== ' netstat -antpecho  ' ======================BootLog=== ===================== ' netstat -secho  ' ======================netstat -s===================== ' lastecho  ' ======================du -sh /etc/=================== ' Du -sh /etc/echo   ' ======================du -sh /boot/================== ' du -sh /boot/echo  ' ===== =================du -sh /dev/=================== ' du -sh /dev/echo  ' ================== ====df -h========================== ' df -hecho  ' ======================mount | column  -t============== ' Mount | column -t}topandvmstat () {top -d 2 -n 1  -bvmstat 1 10}checkgatherlog () {if [ -f  "$LocalServerLogPath/$GetTheIpCommand. Log"  ];then        rm -rf  $LocalServerLogPath/$GetTheIpCommand. logfiif [ !  -x  "$LocalServerLogPath"  ];then    mkdir  "$LocalServerLogPath" Fiif  [ ! -f  "$LocalServerLogPath/$GetTheIpCommand. Log"  ];then     touch  $LocalServerLogPath/$GetTheIpCommand. log    linuxosinformation>>$ localserverlogpath/$GetTheIpCommand. log    performanceinfomation>>$ localserverlogpath/$GetTheIpCommand .log    opratesystemsec>> $LocalServerLogPath/$ Gettheipcommand.log    topandvmstat>> $LocalServerLogPath/$GetTheIpCommand. LOGFI} Checkgatherlogscp_log_to_gather_server= "scp  $LocalServerLogPath/$GetTheIpCommand .log [email  Protected] $GatherServerIpAddress: $GatherServerLogPath "/usr/bin/expect<<eof        set timeout 50         spawn  $SCP _log_to_gather_server         expect {                  "*yes/no)?"                   {                        send  "yes\n"                        "*password:*"  {send  " gatherserverpassword\n "}                  }                   "*password:"                           {                      send  "$GatherServerPassword \ n"                   }                }         expect  "*password:"   { send  "$GatherServerPassword \ n"  }         expect  "100%"          Expect eofeof


File.txt content Form

192.168.182.143 123456192.168.182.129 123456192.168.182.146 123456

Note: 192.168.182.143 is the server password that is patrolled by the server ip,123456 is being patrolled.


Disclaimer: This script filters the results of the patrol with awk and SED, as well as grep, for formatting display and Excel processing. Because of the limited level, if there is a greater God that there is a better solution or the script has improved, please point out. We all learn together and make progress together.

Personal qq:1299039410

This article is from "Turing Manor" blog, please be sure to keep this source http://thinkcoding.blog.51cto.com/4410442/1769207

shell-Batch Patrol Server script

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.