11 月 112022
 
#!/bin/sh

retcode=0
count_retcode() {
    retcode=`expr "0$retcode" + "0$?"`
}

# ......

retcode=0
apt-get -y update; count_retcode
apt-get -y install openssh-server; count_retcode
apt-get -y install apache2; count_retcode

if [ "$retcode" != "0" ]; then
    echo "Failed to install required packages"
    exit 1
fi
11 月 112022
 
#!/bin/sh

help() {
    echo ""
    echo "My Script v1.1"
    echo "Usage: $0 [OPTION] [FILE]"
    echo "    -b        backup server"
    echo "    -r file   restore server with the specific archive file"
    echo ""
    exit 1
}

while getopts "br:" opt; do
    case "$opt" in
        b) ACTION="BACKUP" ;;
        r) ACTION="RESTORE"; RESTORE_FILE="$OPTARG" ;;
        ?) help ;;
    esac
done

[ -z "$ACTION" ] && help
11 月 222016
 

Source: Test from shell script if remote TCP port is open

I’m looking for a quick and simple method for properly testing if a given TCP port is open on a remote server, from inside a Shell script.

I’ve managed to do it with the telnet command, and it works fine when the port is opened, but it doesn’t seem to timeout when it’s not and just hangs there…

Here’s a sample:

l_TELNET=`echo "quit" | telnet $SERVER $PORT | grep "Escape character is"`
if [ "$?" -ne 0 ]; then
  echo "Connection to $SERVER on port $PORT failed"
  exit 1
else
  echo "Connection to $SERVER on port $PORT succeeded"
  exit 0
fi

I either need a better way, or a way to force telnet to timeout if it doesn’t connect in under 8 seconds for example, and return something I can catch in Shell (return code, or string in stdout).

I know of the Perl method, which uses the IO::Socket::INET module and wrote a successful script that tests a port, but would rather like to avoid using Perl if possible.

Continue reading »

7 月 172016
 

Source: Variables validation (name and IP address) in bash

function valid_ip()
{
    ip=$1
    stat=1

    if echo "$ip" | egrep -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' >/dev/null
    then
        # Then the format looks right - check that each octect is less
        # than or equal to 255:
        VALID_IP_ADDRESS="$(echo $ip | awk -F'.' '$1 <=255 && $2 <= 255 && $3 <= 255 && $4 <= 255')"
        if [ -z "$VALID_IP_ADDRESS" ]
        then
            #echo "The IP address wasn't valid; octets must be less than 256"
            stat=1
        else
            #echo "The IP address was valid"
            stat=0
        fi
    else
        #echo "The IP address was malformed"
        stat=1
    fi

    return $stat
}