ITeye博客

linux shell

ericFang · 2010-04-24 01:36 · linux · 编程语言 · Markdown

linux shell

评论(19)

  1. #19 楼 · ericFang · 2011-03-30 17:47

    › 如果脚本文件的第一个字符不是“#”号,则启动bsh执行此脚本 › 如果脚本文件的第一个字符是“#”号,但第二个字符不是“!”,则启动csh执行此脚本 › 如果脚本文件的前两个字符为“#!”,则后面必须是Shell的全路径,启动指定的Shell执行此脚本,

    $0 当前脚本的名字 $1-9 位置参量1~9 ${10} 位置参量10 $# 位置参量的个数 $* 所有的位置参量 $@ 同上 “$*” 扩展为一个 “$@” 扩展为多个

  2. #18 楼 · ericFang · 2011-03-30 17:46

     命令行的处理顺序:  历史记录替换(需要设置)  命令行拆分为Token(以空格和制表符分隔)  历史引用  处理引用  定义别名替换和函数(如果需要)  建立重新定向、后台和管道  变量替换($user等)  命令替换(echo for today is date)  文件名替换  程序执行(内建命令直接执行,否则在PATH变量指定的目录列表中查找)  当Shell准备好执行命令的时候,按如下命令类型顺序执行(type):  别名  关键字  函数  内建命令  可执行程序

  3. #17 楼 · ericFang · 2011-03-30 17:46
    <	重新定向输入($ tr ‘[a-z]’ ‘[a-z]’ < file)
    >	重新定向输出($ ls > file)
    >>	追加输出($ date >> file)
    2>	重新定向错误($ cc prog.c 2> errfile)
    &>(>&)	重新定向错误和标准输出($ find . -name “*.c” -print >& file)
    2>&1	重新定向错误到标准输出($ find . > file 2>&1)
    
    
  4. #16 楼 · ericFang · 2010-12-01 15:06

    http://linux.chinaunix.net/bbs/thread-1174532-1-1.html

  5. #15 楼 · ericFang · 2010-09-27 11:40

    远程执行命令: ssh_run.sh $1 user password "cmd"|grep rac|xargs ssh_run.sh:

    #!/usr/bin/expect
    
    if {$argc!=4 && $argc!=5} {
        send_user "Usage: $argv0 {host} {username} {password} {cmdline} {timeout}\n\n"
        exit 1
    }
    
    set HOST       [lindex $argv 0]
    set USER       [lindex $argv 1]
    set PASSWD     [lindex $argv 2]
    set CMD        [lindex $argv 3]
    set TIMEOUT    [lindex $argv 4]
    set done       0
    
    if { $TIMEOUT == "" } {
        set TIMEOUT 15
    }
    
    
    proc remove_known_hosts_entry {host} {
        regsub ".*/" $::argv0 "" name
        set tmp_file "/tmp/$name.tmp"
        set known_hosts "$::env(HOME)/.ssh/known_hosts"    
        if {[catch {
        set fd_known_hosts [open $known_hosts r]
        set fdTmp [open $tmp_file w]
        while 1 {
            gets $fd_known_hosts line
            if [eof $fd_known_hosts] {
            break
            }
            if [regexp "(\[^, ]+,)*${host}(,\[^, ]+)* " $line] {
            continue
            }
            puts $fdTmp $line
        }
        close $fd_known_hosts
        close $fdTmp
        file rename -force $tmp_file $known_hosts
        } error]} {
        send_user "$error\n"
        exit 2
        }
    }
    
    set timeout    ${TIMEOUT}
    spawn -noecho ssh ${USER}@${HOST} "$CMD"
    while { 1 } {
        expect {
            timeout { exit 4 }
            -nocase -re "Permission denied*" { exit 3 }
            "@@@@@@@@@@@@@@@@@@@@" { 
            remove_known_hosts_entry $HOST 
            spawn -noecho ssh ${USER}@${HOST} "$CMD"
            }
            -nocase -re "yes/no" { send "yes\n" }
            -nocase -re "password: " { send "${PASSWD}\n" }
            -nocase "try again" { exit 3 }
            eof { exit 0 }
        }
    }
    
    
    
  6. #14 楼 · ericFang · 2010-08-18 17:10
    #!/usr/bin/expect
    
    spawn ssh -q 172.16.128.0
    set timeout 600
    expect {
        timeout {exit 2}
        -nocase -re "Password:"  {send "huawei\r"}
           }
    
    expect {
        -nocase -re "password:" {exit 3}
        "omu*"
    }
    send "rm -r /opt/output\r"
    send "exit\r"
    
    spawn scp -r [lindex $argv 0] 172.16.128.0:/opt
    expect "*Password:"
    send "huawei\n"
    expect "fdsfds"
    send "exit\r"
    
    
  7. #13 楼 · ericFang · 2010-08-12 10:19
    function echo_OK ()
    {
        echo_attention "INFO" "OK"
    }
    
    function echo_FAIL ()
    {
        echo_attention "ERROR" "FAIL"
    }
    function rollback_data()
    {
            truncate_table="sqlplus -S dbo/huawei <<! 2>/dev/null
               set head off
               TRUNCATE TABLE T_PCC_SUBSCRIBER;
               commit;
               quit
            !"
            truncate_table_result=$(su - oracle -c "${truncate_table}")
            echo ${truncate_table_result}>>${log_file}
            exe_roll="imp dbo/huawei file=${bak_file_dmp} full=y ignore=y"
            local TMP_SH_FILE=/opt/UpdateMsisdnTool/AA.SH
            echo ${exe_roll} > ${TMP_SH_FILE}
            su - oracle -c "bash ${TMP_SH_FILE}">${log_file} 2>&1
            #roll_result=$(su - oracle -c "${exe_roll}")
            return 0
    }
    
    
    
    
  8. #12 楼 · ericFang · 2010-08-11 19:19
    function echo_step()
    {
        if [ "$1" = "" ] || [ "$2" = "" ]
        then
            echo "$@"
            return
        fi
    
        stepStr=$2
        stepStr="${stepStr}"" ............................................. "
        echolen=`tput cols` 2>/dev/null
        if [ "${echolen}" = "" ]
        then
            echolen=45
        elif [ ${echolen} -gt 75 ]
        then
            echolen=58
        elif [ ${echolen} -lt 15 ]
        then
            echolen=10
        else
            let echolen=echolen-10
        fi
    
        stty echo 2>/dev/null
              case "$1" in
            "1")
                stepStr=${stepStr:0:$echolen}
    
                step_num=`expr ${step_num} + 1`
                if [ ${step_num} -le 9 ]
                then
                    step_num="0${step_num}"
                fi
                new_sub_step_flag=1
    
                echo -e -n "[`date +%h:%m:%s`]NOW${step_num}: ${stepStr}"
                ;;
            "2")
                if [ $new_sub_step_flag -eq 1 ]
                then
                    substep_num=0
                    new_sub_step_flag=0
                fi
    
                let echolen=echolen-10
                stepStr=${stepStr:0:$echolen}
    
                substep_num=`expr $substep_num + 1`
                if [ ${substep_num} -le 9 ]
                then
                    step_num="0${substep_num}"
                fi
    
                echo -n "[`date +%h:%m:%s`]    Step${step_num}.${substep_num}: ${stepStr}"
                ;;
            "reset")
                step_num=0
                ;;
              *)
                echo -n "$@"
                ;;
        esac
    }
    
    
    
  9. #11 楼 · ericFang · 2010-08-11 19:16

    function echo_attention () { stty echo 2>/dev/null

    if ; then
        return ${SUCC}
    fi
    
    if ; then
        echo "$1"
        return ${SUCC}
    fi
    
    case "$1" in
        "INFO")
            echo -e "\033
    
  10. #10 楼 · ericFang · 2010-06-12 15:27

    sed http://bbs.chinaunix.net/viewthread.php?tid=605565

  11. #9 楼 · ericFang · 2010-06-09 11:35

    #!/bin/bash backup_conf() { prtmsg -nprt "Backup config files!" cp /etc/init.d/rm9000sys ${CONF}/conf_bak/rm9000sys cp /opt/RM9000/autorun/S20RM9000MONITOR.sh ${CONF}/conf_bak/S20RM9000MONITOR.sh > /dev/null 2>&1 cp ${RM9000_PMS}/pms/conf/dmf/treecache.xml ${CONF}/conf_bak/treecache.xml cp ${RM9000_PMS}/pms/conf/dmf/hibernate.cfg.xml ${CONF}/conf_bak/hibernate.cfg.xml cp ${RM9000_PMS}/pms/jboss-4.0.5.GA/server/rm9000/deploy/cluster-service.xml ${CONF}/conf_bak/cluster-service.xml cp ${RM9000_PMS}/pms/conf/maf/maf-mbean-config.xml ${CONF}/conf_bak/maf-mbean-config.xml }

    copy_conf() { prtmsg -nprt "Copy config files to server from $1" cp $1/rm9000sys /etc/init.d/rm9000sys cp $1/treecache.xml ${RM9000_PMS}/pms/conf/dmf/treecache.xml cp $1/hibernate.cfg.xml ${RM9000_PMS}/pms/conf/dmf/hibernate.cfg.xml cp $1/cluster-service.xml ${RM9000_PMS}/pms/jboss-4.0.5.GA/server/rm9000/deploy/cluster-service.xml cp $1/maf-mbean-config.xml ${RM9000_PMS}/pms/conf/maf/maf-mbean-config.xml }

    creat_new_conf() { if then sed '88i<FD_SIMPLE timeout="2000" max_missed_hbs="5"/>' ${RM9000_PMS}/pms/conf/dmf/treecache.xml| sed 's/shun="true"/shun="false"/' | sed 's/48866/998/' > ${CONF}/treecache.xml else sed 's/shun="true"/shun="false"/' ${RM9000_PMS}/pms/conf/dmf/treecache.xml|sed 's/48866/998/' > ${CONF}/treecache.xml fi

         if 
         then
                 sed '20i<property name="dbconnection.logintimeout">10</property>' ${RM9000_PMS}/pms/conf/dmf/hibernate.cfg.xml | sed 's/"c3p0.timeout">0/"c3p0.timeout">120/' | sed 's/c3p0.max_statements">1000/c3p0.max_statements">0/' > ${CONF}/hibernate.cfg.xml
         else 
    	     sed 's/"c3p0.timeout">0/"c3p0.timeout">120/' ${RM9000_PMS}/pms/conf/dmf/hibernate.cfg.xml | sed 's/c3p0.max_statements">1000/c3p0.max_statements">0/' > ${CONF}/hibernate.cfg.xml
         fi
         
         sed 's/45566/999/' ${RM9000_PMS}/pms/jboss-4.0.5.GA/server/rm9000/deploy/cluster-service.xml|sed 's/shun="true"/shun="false"/' > ${CONF}/cluster-service.xml
         sed -e 's/od>*<\/db/od>5000<\/db/' ${RM9000_PMS}/pms/conf/maf/maf-mbean-config.xml > ${CONF}/maf-mbean-config.xml
    

    }

    conf_main() { if then backup_conf creat_new_conf copy_conf "${CONF}" cp ${CONF}/timezone /opt/RM9000/.timezone rm -f /opt/RM9000/autorun/S20RM9000MONITOR.sh pids=ps -ef|grep bash|grep Monitor_Rm9000.sh|awk '{print $2}' for pid in $pids; do kill -9 $pid >/dev/null 2>&1 done rm -f -r /opt/RM9000/pms/pms/jboss-4.0.5.GA/server/rm9000/deploy/snmp-adaptor.sar rm -f /etc/init.d/rc5.d/*rm9000sys rm -f /etc/init.d/rc3.d/*rm9000sys prtmsg -nprt $(chkconfig -a rm9000sys)

    elif 
    then
         rm -f /opt/RM9000/.timezone
             #cp ${CONF}/conf_back/S20RM9000MONITOR.sh /opt/RM9000/autorun/S20RM9000MONITOR.sh
         #bash /opt/RM9000/autorun/S20RM9000MONITOR.sh
             copy_conf "${CONF}/conf_bak"
    fi
    

    }

    conf_main

  12. #8 楼 · ericFang · 2010-06-09 11:34

    tools.sh #!/bin/bash do_d2u() { echo " start to convert files type from dos to unix" for f in find $1 -print | grep -v 'backup' | grep '\.sh$\|\.$' do if then if then return fi dos2unix "$f" fi done echo " finished" }

    clearDir() { for f in $(find $1 -print ) do if ; then continue fi rm -vf $f done }

    rm_emp_dir() { for f in $(find $1 -print | sort -r) do if ; then rmdir -v $f fi done } main() { if ; then echo "para is error" exit fi

    opcode=$1
    case "$opcode" in
    	"-d2u")
    	d2u $2
    	;;
    	"-clear")
    	clearDir $2
    	;;
    	"-rm")
    	rm_emp_dir $2
    	;;
    	*)
    	echo "operaction is not supported!"
    	;;
    esac
    

    } main $@

  13. #7 楼 · ericFang · 2010-05-28 09:51

    prtmsg() { colorflg=0 # color display while ; do case "$1" in -nprt) colorflg=-1; logflg=0 shift ;; -log) colorflg=-1; logflg=1 shift ;; -info) if ; then colorflg=1; logflg=1; fi shift ;;

                -error)     if ; then colorflg=3; logflg=1; fi
                            shift
                            ;;
    
                -warn)      if ; then colorflg=2; logflg=1; fi
                            shift
                            ;;
    
                *)          msg="$@"
                            break
                            ;;
                esac
        done
    
        case $colorflg in
                1)      echo -n -e "\033; then
                printf "$msg \n"
        fi
        if ; then
                echo -n -e "\033 " >>${LOG}/detail.log
    
        printf "$msg \n"  >>${LOG}/detail.log
    

    }

  14. #6 楼 · ericFang · 2010-05-27 17:27

    netstat -ant|grep 5566 netstat -adu 查看UPD端口的监听 dos2unix 功能是将DOS/MAC下的文件转化为UNIX的文本文件格式 cat ${file_name}|awk -F : '{print $2}' 查出指定文件中以:分隔的行的第二列的内容 grep password ${file_name}|cut -d: -f2 查出指定文件中含password的行并以:分隔的第二列的内容 ping ${ip} -c 1 -w 1 > /dev/null 2>&1 :ping 命令只执行1秒,并将输出的打印输出到垃圾箱

    find ${FILE_PATH} -type f -mtime +${duration} -exec rm {} ;

    find /opt/export_apn/output -type f -mtime +1 lsof -i:1521 | grep rm

  15. #5 楼 · ericFang · 2010-05-21 10:15

    export.conf配置文件参数的说明:

    参数 意义 取值范围 备注 第一列 分钟 1-59 *表示每分钟都执行导出任务 第二列 小时 1-23 0表示子夜,*表示每小时都执行导出任务 第三列 日 1-31 *表示每天都执行导出任务 第四列 月 1-12 *表示每月都执行导出任务 第五列 星期 0-6 0表示星期天,*表示每星期都执行导出任务 注意:请不要修改第六列SCRIPT,并将参数以空格隔开,建议配置在业务量较低的时间执行。

    apn.conf配置范例: ip:8.1.240.36 user:eric password:eric directory:file duration:6

         apn.conf配置范例解释:
    		ip:8.1.240.36   --表示FTP服务器的IP为8.1.240.36
    		user:eric       --表示登录FTP服务器的用户名为eric
    		password:eric   --表示登录FTP服务器的用户密码为eric 
    		directory:file    --表示生成的文件上传到FTP服务器的file目录下
    		duration:6      --表示PDU单板上生成的文件只保留6天以内的文件
    
  16. #4 楼 · ericFang · 2010-05-21 10:14

    目录结构如下(可执行tree命令查看): |-- apn_sub.sh |-- conf | |-- apn.conf | `-- export.conf |-- log |-- output |-- run.sh |-- upload.sh

       apn_sub.sh 主要实现从数据库导出数据并写到文件        
       conf目录存储的是配置文件
       apn.conf存储ftp服务器相关信息和文件保留天数
       export.conf 存储定时任务的执行时间
       log目录存储工具运行的日志文件
       output目录存储生成的文件
       run.sh主要实现让工具定时执行功能
       upload.sh主要实现将output目录下生成的文件上传到指定的ftp服务器目录下
    
  17. #3 楼 · ericFang · 2010-05-21 10:12

    upload.sh

    #!/bin/bash function def_global_var() { SUCC=0 FAIL=1 WORK_DIR=/opt/export_apn OUTPUT_DIR=${WORK_DIR}/output LOG_DIR=${WORK_DIR}/log

    CONF_FILE=${WORK_DIR}/conf/export.conf
    LOG_FILE=${LOG_DIR}/export.log
    
    >${LOG_FILE}
    EXPORT_SCRIPT=apn_sub.sh
    
    return ${SUCC}
    

    }

    function base_check() { if ; then echo_log "Current user must be 'root'" exit ${FAIL} fi

    current_patition=opt
    remain_space=`df|grep "$current_patition" | awk {'print $4'}`
    if ;then
        echo_log "There is no enough space for data export on patiton ${current_patition}."
        return ${FAIL}
        > ${WORK_DIR}/conf/export.conf.bak
        > ${WORK_DIR}/conf/export.conf.tmp
        crontab -u root -l | grep -v "^#" > ${WORK_DIR}/conf/export.conf.bak 2>&1   
        tag=`cat ${WORK_DIR}/conf/export.conf.bak | grep -v "^#" | grep -ic "${EXPORT_SCRIPT}"`    
        if ;then
            sed '/'${EXPORT_SCRIPT}'/d' ${WORK_DIR}/conf/export.conf.bak > ${WORK_DIR}/conf/export.conf.tmp       
    else
            cat  ${WORK_DIR}/conf/export.conf.bak > ${WORK_DIR}/conf/export.conf.tmp
        fi
        
        crontab -u root ${WORK_DIR}/conf/export.conf.tmp > ${LOG_FILE} 2>&1
        result=$?
        if ;then 
            echo_log "Remove crontab fail."   
            return ${FAIL}
        fi    
        echo_log "The registration for data export has been removed."     
        exit 0
    fi
    
    return ${SUCC}
    

    }

    function echo_log() { local date_time=date '+%Y%m%d:%H%M%S' # echo "$1" echo "&{date_time} $1" >> ${LOG_FILE}
    return ${SUCC} }

    function regist_export() { if ;then echo_log "The configuration file ${CONF_FILE} for registration is not existed." return ${FAIL} fi

    > ${WORK_DIR}/conf/export.conf.bak
    > ${WORK_DIR}/conf/export.conf.tmp
    crontab -u root -l | grep -v "^#" > ${WORK_DIR}/conf/export.conf.bak  2>&1      
    tag=`cat ${WORK_DIR}/conf/export.conf.bak | grep -v "^#" | grep -ic "${EXPORT_SCRIPT}"`    
    if ;then
        sed '/'${EXPORT_SCRIPT}'/d' ${WORK_DIR}/conf/export.conf.bak > ${WORK_DIR}/conf/export.conf.tmp       
    else
        cat ${WORK_DIR}/conf/export.conf.bak > ${WORK_DIR}/conf/export.conf.tmp
    fi
    
    sed "s|SCRIPT|${WORK_DIR}/${EXPORT_SCRIPT} |" ${WORK_DIR}/conf/export.conf  >> ${WORK_DIR}/conf/export.conf.tmp
    
    crontab -u root ${WORK_DIR}/conf/export.conf.tmp > ${LOG_FILE} 2>&1
    result=$?
    if ;then 
        echo_log "The format of the configuration file ${CONF_FILE} is not correct."   
        return ${FAIL}
    fi 
    
    /etc/init.d/cron restart > ${LOG_FILE} 2>&1  
    echo_log "The data export task has been registrated in your system successfully."    
    return ${SUCC}
    

    }

    function main() { def_global_var base_check tag=$? if ; then echo_log "callback base_check function return fail" exit ${tag} fi regist_export return ${SUCC} }

    main $@

  18. #2 楼 · ericFang · 2010-05-21 10:12

    upload.sh #!/bin/bash function echo_log() { local date_time=date '+%Y%m%d:%H%M%S' #echo "$1" echo "${date_time} $1" >> /opt/export_apn/log/apn_sub.log return 0 } file_name=/opt/export_apn/conf/apn.conf ip=grep ip ${file_name} |cut -d: -f2 if ;then ping ${ip} -c 1 -w 1 > /dev/null 2>&1 if ;then echo_log " Ftp ip is invalid !" exit
    fi else echo_log "Ftp ip is must !" exit fi user=grep user ${file_name}|cut -d: -f2 password=grep password ${file_name}|cut -d: -f2 directory=grep directory ${file_name}|cut -d: -f2 if ;then echo_log "Ftp directory is must !" exit fi upload_file_name=$1 if ;then upload_file_name=* fi re=ftp -n -v ${ip} << END user ${user} ${password} binary hash cd ${directory} lcd /opt/export_apn/output prompt mput ${upload_file_name} bye END is_flag=echo ${re}|grep "Not logged" |wc -l if ;then echo_log "Ftp user or password error!!" else
    is_flag=echo ${re}|grep "successfully" |wc -l if ;then echo_log "Ftp upload file successfully" else echo_log "Ftp Connection excption!" fi
    fi

  19. #1 楼 · ericFang · 2010-05-21 10:11

    apn_sub.sh #!/bin/bash WORK_DIR=/opt/export_apn LOG_FILE=${WORK_DIR}/log/apn_sub.log FILE_PATH=${WORK_DIR}/output RESERVE_NUM=6 function echo_log() { local date_time=date '+%Y%m%d:%H%M%S' #echo "$1" echo "${date_time} $1" >> ${LOG_FILE}
    return 0 } function export_apn_count() { local create_time=date '+%Y-%m%d-%H%M%S' file_name=apn_sub_count${create_time}.csv local apn_sub_count=${FILE_PATH}/${file_name} res="sqlplus -S dbo/huawei <<! >/dev/null 2>&1 set head off set trimout on set trimspool on set newpage none set feedback off spool ${apn_sub_count} select 'APN,SUBSCRIBER AMOUNT' FROM DUAL; select s.apn||','||count(distinct sp.SUBSCRIBERID) from T_SERVICE s ,T_PCC_SUBSCRIPTION sp where s.apn is not null and s.id=sp.SERVICEID group by s.apn; spool off quit !" result1=$(su - oracle -c "${res}") tag=head -10 ${apn_sub_count}|grep -c 'ORA-' if ; then echo_log "Export apn data to ${apn_sub_count} fail!! " fi return ${tag} }

    function export_apn_info() { local create_time=date '+%Y-%m%d-%H%M%S' file_name=apn_sub_info${create_time}.csv local apn_sub_info=${FILE_PATH}/${file_name} res="sqlplus -S dbo/huawei <<! >/dev/null 2>&1 set head off set trimout on set trimspool on set newpage none set feedback off spool ${apn_sub_info} select 'SUBSCRIBER Id,MSISDN' FROM DUAL; select distinct P.SUBSCRIBERIDENTIFY,',',P.MSISDN from T_SERVICE S,T_PCC_SUBSCRIBER P,T_PCC_SUBSCRIPTION SP where S.APN='$1' AND S.ID=SP.SERVICEID AND SP.SUBSCRIBERID=P.ID; spool off
    quit !" result1=$(su - oracle -c "${res}") tag=head -10 ${apn_sub_info}|grep -c 'ORA-' if ; then echo_log "Export apn data to ${apn_sub_info} fail!! " fi return ${tag} }

    检测数据库

    function check_db() { tag=" lmtruntime -5 sqlplus -S / as sysdba <<! 2>/dev/null set head off select open_mode from v\$database; quit !" result=$(su - oracle -c "${tag}") if ; then return 1 fi return 0 }

    function del_file() { local duration=grep duration ${WORK_DIR}/conf/apn.conf|cut -d: -f2 local date_time=date '+%Y%m%d' local del_re=find ${FILE_PATH} -type f -mtime +${duration} -exec rm {} \; return 0 }

    function main() { del_file if ; then echo_log "Current user must be 'root'" exit fi check_db tag=$? if ; then echo_log "The database is invalid" exit fi if ; then export_apn_info $1 else
    export_apn_count fi

    tag=$?
    if ; then
        echo_log "callback export_apn function  fail!! "
        exit ${tag}
    fi
    

    /${WORK_DIR}/upload.sh ${file_name} return 0 }

    main "$@"

评论功能维护中,当前仅展示历史评论。