在bash中构建一个杀手级脚本

时间:2013-06-24 17:17:14

标签: bash while-loop pipe netstat

我一直在尝试学习bash中的逻辑语句的语法,如何做/ if,管道和东西。我正在尝试构建一个bash脚本,但是在3小时没有得到这些东西如何工作之后我失败了。

现在我需要这个小脚本,我会尝试使用通用代码来解释它,或者根据需要调用它。你走了:

while variable THRESHOLD = 10

{
if netstat -anltp contains a line with port 25565
then set variable THRESHOLD to 0 and variable PROCNUM to the process number,
else add 1 to variable THRESHOLD
sleep 5 seconds
}
kill the process No. PROCNUM
restart the script

基本上,它的作用是,一旦套接字关闭,经过几次尝试,就会终止正在侦听该端口的进程。

我很确定这是可能的,但我无法弄清楚如何正确地做到这一点。主要是因为我不懂管道而且我对grep并不熟悉。提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

    #!/bin/bash
    # write a little function
    function do_error {
        echo "$@" 1>&2
        exit 1
    }
    # make the user pass in the path to the executable
    if [ "$1" == "" ]; then
        do_error "USAGE: `basename $0` <path to your executable>"
    fi
    if [ ! -e $1 ]; then
        do_error "Unable to find executable at $1"
    fi
    if [ ! -x $1 ]; then
        do_error "$1 is not an executable"
    fi
    PROC="$1"
    PROCNAME=`basename $PROC`

    # forever
    while [ 1 ]; do
        # check whether the process is up
        proc=`ps -ef | grep $PROCNAME 2>/dev/null`
        # if it is not up, start it in the background (unless it's a daemon)
        if [ "$proc" == "" ]; then
            $PROC &
        fi
        # reinitialize the threshold
        threshold=0
        # as long as we haven't tried 10 time, continue trying
        while [ threshold -lt 10 ]; do
            # run netstat, look for port 25565, and see if the connection is established. 
            # it would be better to checks to make sure
            # that the process we expect is the one that established the connection
            output=`netstat -anp | grep 25565 | grep ESTABLISHED 2>/dev/null`
            # if netstat found something, then our process was able to establish the connection
            if [ "$output" != "" ]; then
                threshold = 0
            else
                # increment the threshold
                threshold=$((threshold + 1))
            fi
            # i would sleep for one second
            sleep 1
        done
        kill -9 $PROCNUM
    done

答案 1 :(得分:1)

不要想要冒犯,但如果你能写一个“通用”程序,你需要学习while的{​​strong>语法,if用于bash和阅读grepkill的手册页,依此类推......

pipes与您的花园中的相同。有两件事:tappond。您可以通过多种方式填充池塘(例如下雨)。此外,您可以打开水龙头。但如果你想用水龙头装满水,需要一根烟斗。就这样。语法:

tap | pond
  • 来自水龙头的输出
  • 连接管道
  • 到池塘的(输入)

e.g。

netstat | grep
  • netstat
  • 的输出
  • 连接管道
  • grep
  • 的输入

这都是魔术......:)

关于语法:您将问题标记为bash

因此,对于bash while syntax的Google搜索会向您显示此初学者Bash指南

http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_09_02.html

到,您可以在同一网站上阅读if

简直无法相信,在3小时后你无法理解用bash语法编写程序的基本whileif语法 - 尤其是当你能编写一个“通用”程序时。

是不是很难(通过修改上一页中的第一个例子)来写:

THRESHOLD="0"
while [ $THRESHOLD -lt 10 ]
do
    #do the IF here
    THRESHOLD=$[$THRESHOLD+1]
done

依旧......