Host Ping Service Start script? - linux

I need some help with a Linux shell script which should automatically check if a host is reachable. It is best to ping port 22 every 3-5 seconds. If the port is reachable the program should execute the command service HelloWorld stop. If the host is not reachable, the script should automatically execute a command on the computer e.g. service HelloWorld start.
Does anyone know how to implement this?
I have something like this, but that not functionning,
#!/bin/bash
IP='192.168.1.1'
fping -c1 -t300 $IP 2>/dev/null 1>/dev/null
if [ "$?" = 0 ]
then
service helloworld stop
else
service helloworld start
fi

Try the following code
#!/bin/bash
IP='192.168.1.1'
PORT=22
(echo >/dev/tcp/$IP/$PORT) &>/dev/null
if [ "$?" = 0 ]
then
service helloworld stop
else
service helloworld start
fi
In this way, it's allowed to check IP with specific port is reachable or not

Related

Script to check connection every 5 minutes and write result to file (without ping) in 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.

CentOS Network Interface Post-Up Script Not Executing

I am running CentOS 7.2, and I'm struggling to get a simple script to execute on ifup of any interface.
My /sbin/ifup-local looks like this:
[root#oracle2 ~]# cat /sbin/ifup-local
#!/bin/bash
if [[ "$1" == "eth0" ]]
then
exec /vpnup
fi
[root#oracle2 ~]#
The referenced script /vpnup looks like this:
[root#oracle2 ~]# cat /vpnup
#!/bin/bash
#
# CompanyX Production L2TP VPN - UP
#
#
echo -e "\n"
echo -e "PLEASE WAIT\n"
echo -e "Dialling Production L2TP VPN... \n"
echo -e ".........................................\n"
ipsec auto --up L2TP-PSK && echo "c qvprodvpn" > /var/run/xl2tpd/l2tp-control
echo -e ".........................................\n"
echo "Connected..."
echo "Adding local static route to manage VPN bound traffic..."
sleep 6s
ip route add 10.10.24.0/24 via 10.10.24.51
echo "Route added..."
echo -e "...\n"
[root#oracle2 ~]#
Fairly simple, the script works fine when called at command line. It just dials into a L2TP VPN that I've setup, to get this box access to the production LAN of another segment of their network.
However, if I execute "service network restart" or indeed "systemctl restart network.service", the VPN interface does not come up, nor does the ip route get added. If I manually execute ifdown eth0, and then ifup eth0, it also does not run the script as intended.
If I execute "/sbin/ifup-local eth0" the script runs as expected, so I know my script is fine, and I know my ifup-local is fine.
Am I missing something obvious? I've never worked with pre/post up scripts before, but I always figured they were pretty simple... Was I wrong?
Ensure your ifcfg-eth0 script includes
NM_CONTROLLED=no
Otherwise, calling systemctl restart network or ifup eth0 will not execute ifup-pre-local, ifup-eth, ifup-post, ifup-local, etc. for eth0. They will still be called for lo, though.

How can I check to see if an SSH server is listening on a host without actually attempting a login

I am trying to make a bash script which checks to see if a host exists and then attempts to ssh into it if an SSH server is listening on the host. The command would default to telnet if an SSH server is not listening.
What would be the best way to do this? I was thinking about using something like ssh-keyscan to just grab the public key from the ssh server, but ssh-keyscan is not on this jumpserver. Nmap is not on this server either. I'm not able to copy those binaries onto the jump server, nor am I able to compile/build anything on the jumpserver.
What would be the best way to go about checking for an SSH server? I think expect might work, though I would like to avoid using that if possible.
Just check your ability to connect to it, if your bash has the necessary (/dev/tcp) extension; this requires no external commands whatsoever:
if (exec 2>/dev/null 4>/dev/tcp/"$hostname"/22); then
echo "port is open"
else
echo "unable to connect"
fi
Note that your script will need to start with #!/bin/bash, not #!/bin/sh, for this to work.
You can write a shell script and use telnet command to find remote port status
[root#box ~]# telnet remote.example.com 22
Trying 192.168.100.1...
Connected to remote.example.com.
Escape character is '^]'.
SSH-2.0-OpenSSH_5.3
Sample script:
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 love oneliners :)
if nc "server" "port" </dev/null >/dev/null 2>&1;then echo yeah;else echo no;fi
works on my router and on my rpi

Error in linux script

I have written the below script to check whether my server running fine or not.But it is not properly working.It always showing Not runing even if it is running fine.Also the telnet in the script is not running working properly .Can any one help?
#!/bin/sh
export smtp=smtprelay.intra.xxx.com:25
Connect_redmine(){
telnet redmine.intra.xxx.com 443 <<EOF
exit 1;
EOF
}
Connect_redmine>/home/ssx00001/log_connect.txt
grep "Connected" /home/ssx00001/log_connect.txt
status=$?
if [ $status == 0 ]; then
echo `date` "Redmine PROD server is running fine"|mailx -r Redmine#xxx -s "Redmine PROD server is running" 777.p#xxx.com
else
echo "Redmine PROD server is not Running"|mailx -r redmine#xxx.com -s "Redmine PROD server is not running" 777.p#xxx.com
fi
A couple of questions first:
1] What does redmine do? Is it just a HTTPS server?
2] If [1] is true, can you do a wget of the index page, and use the result of that? It should be a lot easier to parse.
3] Telnetting into a HTTPS server, as far as I know, won't work, because it's not doing any of the handshaking that would be necessary for an SSL connection (which needs to occur before any content will be sent).
Using wget, you can do something like this:
wget https://redmine.intra.xxx.com/index.html
if [[-f "index.html" ] && [ -s "index.html" ]]
then
# The service is live
else
# Something is wrong
fi

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