linux script with netcat stops working after x hours

后端 未结 6 1874
闹比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:52

    About the loop it could look like this.

    #!/bin/bash
    
    for (( ;; ))
    do
        netcat -lk -p 12345 | while read line
        do
            match=$(echo "$line" | grep -c 'Keep-Alive')
            if [ "$match" -eq 1 ]; then
                [start a command]
            fi
        done
        sleep 4s
    done
    

    with added double quotes to keep it safer.

    And you could try capturing errors and add some logging with this format:

    #!/bin/bash
    
    {
        echo "[$(date "+%F %T")] Starting loop."
    
        for (( ;; ))
        do
            echo "[$(date "+%F %T")] Starting netcat."
    
            netcat -lk -p 12345 | 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
    

    Your read command could also be better in this format since it would read lines unmodified:

    ... | while IFS= read -r line
    

    Some could also suggest the use of process substitution but I don't recommend it this time since through the | while ... method the while loop would be able to run on a subshell and keep the outer for loop safe just in case it crashes. Besides there isn't really a variable from the while loop that would be needed outside of it.

    I'm actually having the idea now that the issue might actually have been related to the input and how the while read line; do ...; done block handles it and not netcat itself. Your variables not being quoted properly around "" could be one of it, or could probably be the actual reason why your netcat is crashing.

提交回复
热议问题