Script to check connection every 5 minutes and write result to file (without ping) in LINUX - linux

I need to check my connection to a spesific port every 5 minutes, currently i can't use ping command, so i need other alternative to do this.I want to execute this command in shell script
Can someone help me to show some example for this case?

port=80
ip=8.8.8.8
checkIntervalSecs=5
timeoutSecs=1
while true ; do
if $(nc -z -v -w$timeoutSecs $ip $port &>/dev/null); then
echo "Server is up!"
else
echo "Server is down!"
fi
sleep $checkIntervalSecs
done
This runs until you kill it. For an explanation of the nc command, it is basically taken from SO question #IporSircer suggested.

Related

How to capture the output of telnet command in a variable in Shell script

I need to run the telnet command on a remote server using shell script and have to capture the output. When i execute the below, it is not getting completed but instead getting hung. Can someone please advise how to terminate or timeout the telnet command using shell script once it is executed.
telnet_output=`telnet $server $port`
echo "Output is $telnet_output"
I tried writing it to a file as well. But this is also getting hung when executed in remote server.
opfile="telop.log"
telnet_output=`telnet $server $port | tee $opfile`
op=`cat $opfile`
echo "$op"
Try this :
telnet_output="$({ sleep 1; echo $'\e'; } | telnet $server $port 2>&1)"
printf "Output is\n%s\n" "$telnet_output"
echo $'\e' sends an escape character to telnet to terminate it.

Stopping the Ping process in bash script?

I created a bash script to ping my local network to see which hosts is up and I have a problem in stopping the Ping process by using ctrl+C once it is started
the only way i found to suspend it but even the kill command doesn't work with the PID of the Ping
submask=100
for i in ${submask -le 110}
do
ping -n 2 192.168.1.$submask
((submask++))
done
Ctrl + C exit ping, but another ping starts. So you can use trap.
#!/bin/bash
exit_()
{
exit
}
submask=100
while [ $submask -le 110 ]
do
fping -c 2 192.168.77.$submask
((submask++))
trap exit_ int
done
I suggest you to limit the amount of packets sent with ping with the option -c.
I also corrected the bash syntax, guessing what you intend to do.
Finally, it is faster to run all the ping processes in parallel with the operand &.
Try:
for submask in ${100..110}
do
echo ping -c 1 192.168.1.$submask &
done

Shell script to find out if a port is being listened to using netstat?

I have a server where a certain port (9999) is being listened to by a PHP socket server. What happens is that devices can connect to the socket and send messages. The code works fine right now, however, I noticed that the socket would sometimes close or die off, and I need to be able to put it back up online automatically without me having to log in and run it again.
What I'm thinking of is writing a Shell script that would check via netstat if there's a process running on port 9999, and if there's none, the script would trigger the PHP socket server to go online again. This Shell script would then be called by Cron every 1 or 2 minutes to check if the PHP socket is running.
I have bare minimum knowledge about Shell scripting, and so far, this was the only other thing I wrote in Shell:
#!/bin/sh
if pidof "my process name here" >/dev/null; then
echo "Process already running"
else
echo "Process NOT running!"
sh /fasterthancron.sh
fi
I think I should be able to reuse this code to some degree but I'm not sure what to replace the if condition with.
I have the idea that I'm supposed to use netstat -tulpn to figure out what processes are running, but I'm not sure how to filter through that list to find if a specific process is running on port 9999.
If you use netstat -tlpn (or its replacement ss -tpln), you can grep for 9999 and look for processes listening on it under "Local Address".
ss -tpln | awk '{ print $4 }' | grep ':9999'
Alternatively, if you can, use netcat or telnet instead e.g. nc -v localhost 9999.
if echo -n "\cD" | telnet ${host} ${port} 2>/dev/null; then
...
fi
I wrote something similar a while back: docker-wait
This was forked from aanand's docker-wait
You can use famous netstat -tupln with a simple if/else logic to do this.
if [ -z "$(sudo netstat -tupln | grep 9999)" ];
then
echo notinuse;
else
echo inuse;
fi

Bash: how to check if a command executed in time

I am trying to execute this command expressvpn connect in a bash script to be executed in terminal. The problem is that sometimes it takes too long to connect and I want to make sure it doesn't take too much. I tried this command
some_command
if [ $? -eq 0 ]; then
echo OK
else
echo FAIL
fi
but this is for checking wether the command is executed or not, while I want to make sure that if it is not executed in, say 10 seconds, then the script must stop and start over from the beginning. How do I do that?
Here's the full code
#!/bin/bash
expressvpn disconnect
while (0<1); do
expressvpn connect smart location
xdg-open http://link
sleep 15
xdotool key Control_L+w
expressvpn disconnect
expressvpn refresh
done
I hope I was clear. Thanks in advance.
I hope you find it useful.
timeout 15s expressvpn connect smart location>/dev/null &
You can simply execute this :
timeout 15s expressvpn connect smart location
case "$?" in
0) echo "OK" ;;
124) echo "TIMEOUT" ;;
*) echo "FAIL" ;;
esac
from man timeout
Exit status:
124 if command times out
125 if timeout itself fails
126 if command is found but cannot be invoked
127 if command cannot be found
137 if command is sent the KILL(9) signal (128+9)

How to check if a server is running

I want to use ping to check to see if a server is up. How would I do the following:
ping $URL
if [$? -eq 0]; then
echo "server live"
else
echo "server down"
fi
How would I accomplish the above? Also, how would I make it such that it returns 0 upon the first ping response, or returns an error if the first ten pings fail? Or, would there be a better way to accomplish what I am trying to do above?
I'ld recommend not to use only ping. It can check if a server is online in general but you can not check a specific service on that server.
Better use these alternatives:
curl
man curl
You can use curl and check the http_response for a webservice like this
check=$(curl -s -w "%{http_code}\n" -L "${HOST}${PORT}/" -o /dev/null)
if [[ $check == 200 || $check == 403 ]]
then
# Service is online
echo "Service is online"
exit 0
else
# Service is offline or not working correctly
echo "Service is offline or not working correctly"
exit 1
fi
where
HOST = [ip or dns-name of your host]
(optional )PORT = [optional a port; don't forget to start with :]
200 is the normal success http_response
403 is a redirect e.g. maybe to a login page so also accetable and most probably means the service runs correctly
-s Silent or quiet mode.
-L Defines the Location
-w In which format you want to display the response
-> %{http_code}\n we only want the http_code
-o the output file
-> /dev/null redirect any output to /dev/null so it isn't written to stdout or the check variable. Usually you would get the complete html source code before the http_response so you have to silence this, too.
nc
man nc
While curl to me seems the best option for Webservices since it is really checking if the service's webpage works correctly,
nc can be used to rapidly check only if a specific port on the target is reachable (and assume this also applies to the service).
Advantage here is the settable timeout of e.g. 1 second while curl might take a bit longer to fail, and of course you can check also services which are not a webpage like port 22 for SSH.
nc -4 -d -z -w 1 ${HOST} ${PORT} &> /dev/null
if [[ $? == 0 ]]
then
# Port is reached
echo "Service is online!"
exit 0
else
# Port is unreachable
echo "Service is offline!"
exit 1
fi
where
HOST = [ip or dns-name of your host]
PORT = [NOT optional the port]
-4 force IPv4 (or -6 for IPv6)
-d Do not attempt to read from stdin
-z Only listen, don't send data
-w timeout
If a connection and stdin are idle for more than timeout seconds, then the connection is silently closed. (In this case nc will exit 1 -> failure.)
(optional) -n If you only use an IP: Do not do any DNS or service lookups on any specified addresses, hostnames or ports.
&> /dev/null Don't print out any output of the command
You can use something like this -
serverResponse=`wget --server-response --max-redirect=0 ${URL} 2>&1`
if [[ $serverResponse == *"Connection refused"* ]]
then
echo "Unable to reach given URL"
exit 1
fi
Use the -c option with ping, it'll ping the URL only given number of times or until timeout
if ping -c 10 $URL; then
echo "server live"
else
echo "server down"
fi
Short form:
ping -c5 $SERVER || echo 'Server down'
Do you need it for some other script? Or are trying to hack some simple monitoring tool? In this case, you may want to take a look at Pingdom: https://www.pingdom.com/.
I using the following script function to check servers are online or not. It's useful when you want to check multiple servers. The function hide the ping output, and you can handle separately the server live or server down case.
#!/bin/bash
#retry count of ping request
RETRYCOUNT=1;
#pingServer: implement ping server functionality.
#Param1: server hostname to ping
function pingServer {
#echo Checking server: $1
ping -c $RETRYCOUNT $1 > /dev/null 2>&1
if [ $? -ne 0 ]
then
echo $1 down
else
echo $1 live
fi
}
#usage example, pinging some host
pingServer google.com
pingServer server1
One good solution is to use MRTG (a simple graphing tool for *NIX) with ping-probe script. look it up on Google.
read this for start.
Sample Graph:

Resources