linux script with netcat stops working after x hours

后端 未结 6 1872
闹比i
闹比i 2021-02-20 11:20

I\'ve have to scripts:

#!/bin/bash

netcat -lk -p 12345 | while read line
do
    match=$(echo $line | grep -c \'Keep-Alive\')
    if [ $match -eq 1 ]; then
              


        
6条回答
  •  再見小時候
    2021-02-20 11:58

    Periodically netcat will print, not a line, but a block of binary data. The read builtin will likely fail as a result.

    I think you're using this program to verify that a remote host is still connected to port 12345 and 12346 and hasn't been rebooted.

    My solution for you is to pipe the output of netcat to sed, then pipe that (much reduced) line to the read builtin...

    #!/bin/bash
    
    {
        echo "[$(date "+%F %T")] Starting loop."
    
        for (( ;; ))
        do
            echo "[$(date "+%F %T")] Starting netcat."
    
            netcat -lk -p 12345 | sed 's/.*Keep-Alive.*/Keep-Alive/g' | \
            \
            while read line
            do
                match=$(echo "$line" | grep -c 'Keep-Alive')
                if [ "$match" -eq 1 ]; then
                    [start a command]
                fi
            done
    
            echo "[$(date "+%F %T")] Netcat has stopped or crashed."
    
            sleep 4s
        done
    } >> "/var/log/something.log" 2>&1
    

    Also, you'll need to review some of the other startup programs in /etc/init.d to make sure they are compatible with whatever version of rc the system uses, though, it would be much easier to call your script2.sh from a copy of some simple file in init.d. As it stands script2 is the startup script but doesn't conform to the init package you use.

    That sounds more complicated that I mean... Let me explain better:

    /etc/init.d/syslogd        ## a standard init script that calls syslogd
    /etc/init.d/start-monitor   ## a copy of a standard init script that calls script2.sh
    

    As an additional note, I think you could bind netcat to the specific IP that you are monitoring, instead of binding it to the all address 0.0.0.0

提交回复
热议问题