Shell获取Aix/linux/unix机器上db2和os的信息并上传到指定服务器

(之前写过一篇类似的文章,当时传输文件用的是ftp,因为项目觉得ftp不够安全所以这次换成了scp,同时对脚本的一些地方也做了一些调整)

其实做这个东西还是因为项目的需求,需要获取某些机器(目前主要是linux,aix,unix)上的os和db的信息,如果没有db的话给出提示信息,因为机器比较多,也是为了重复利用,因此写了这么一个shell脚本,脚本中要用到的一些关键命令,再前面几篇文章中都有介绍:awk,sed,export,sort;以及查找机器的os和db信息的命令。下面是整个代码:

#!/bin/sh

#获取os的name
name
=$(uname -s -n | awk '{print $2}')

#获取os的ip ip
=$(ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d 'addr:' )

#获取os的系统类型 os
=$(uname -s -n | awk '{print $1}' )

#查找db的inst的路径,后面通过执行该命令来列出db的所有instance dbinstpath
=$(find /opt -name db2ilist|grep 'inst'|sed -n '1,1p') #dbid=$($dbinstpath|sed -n '1,1p')
#判断命令dbinstpath是否为空,如果为空说明该机器上没有db
if test -z "$dbinstpath" then comm="no db2ilist on target computer" osdbinfo=$name","$ip","$os","null","null","null","$comm" "$osdbinfo else
  #如果不为空则执行dbinstpath,列出所有的instance dbinst=$($dbinstpath) if test -z "$dbinst" then echo "there is no any db instance on that server, so can not retrieve db info" > getDBinfo.log 2>&1 else
    #循环取出instance的信息 for i in $dbinst do cmp=$(su - $i|grep "Unable to change directory") if test -z "$cmp" then dbver=$(su - $i -c db2level | grep 'DB2 v' | awk '{print $5}'| tr -d '"|,' ) dbname=$(su - $i -c db2 list db directory | grep 'Database name' | awk '{print $4}' ) comm="_" else comm="can not change to directory for db instance:"$i dbver="null" dbname="null" fi osdbinfo=$name","$ip","$os","$dbver","$dbname","$i","$comm" "$osdbinfo done fi fi
#将取到的os和db下个instance信息写到csv文件 csvtitle
='0os_name, 0os_ip, 0os, 0db_version, 0db_name, 0db_inst' echo $csvtitle" "$osdbinfo > db2info.csv 2>&1
#下面这段主要是上传/下载文件,使用export和scp,其中export用来自动进行和terminor交互,自动输入密码等 svr
="9.83.21.137" echo "expect1" > getDBinfo.log 2>&1 expect <<! echo "expect2" > getDBinfo.log 2>&1 spawn scp -r xman@$svr:/db2info.csv /tmp/db2info.txt echo "expect3" > getDBinfo.log 2>&1 expect { "(yes/no)?" { send "yes " expect "*assword:" {send "1qaz2wsx "} } "*assword:" { send "1qaz2wsx " } } echo "expect4" > getDBinfo.log 2>&1 expect "100%" expect eof !
#这段是给取到的os,db信息进行排序,删除重复的记录 cd
/tmp chmod u+rwx db2info.txt echo $osdbinfo>>db2info.txt 2>&1 sort -u db2info.txt -o db2info.txt sed '/^$/d' db2info.txt>db2info_.txt
#最后将整理好的数据上传到svr服务器,整个过程结束 expect
<<! spawn scp -r /tmp/db2info_.txt xman@$svr:/db2info.csv expect { "(yes/no)?" { send "yes " expect "*assword:" {send "1qaz2wsx "} } "*assword:" { send "1qaz2wsx " } } expect "100%" expect eof !

 这个shell脚本可以直接在目标机器上执行的。这里有个小提示就是,使用scp在linux,unix,aix系统上时没有问题的,因为一般他们都支持ssh protocal, 但是如果要使用scp在linux和windows直接传输的话,需要在windows机器上安装工具如freesshd或者winsshd来让windows机支持ssh protocal,安装后进行一些简单的配置就可以了,具体配置步骤网上应该很多,这里就不赘述了。

原文地址:https://www.cnblogs.com/jingwei/p/4876660.html