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

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

Related

Bash run task via ssh and get stdout, stderr live output to file in background

I am running a python 3 script via ssh, and I want to see the stdout and stderr in a file on the remote server.
Also, I would like to see the file updated live while the script is running and that the script will run in the background so the ssh connection will not wait for the script to finish.
While looking at other questions, I managed to answer most of my requests.
Here is what I come up with:
ssh user#machine_ip "(python3 my_script.py 2>&1 | tee output.log) &"
The problem is that the ssh is waiting for the script to finish.
So combining the answer from this question with some hackidy hack nonsense...
Really all you need to do is this:
(( python3 my_script.py 0<&- 2>&1 | tee -a ${OUTFILE} | nc -kl ${PORT} &) &)
Explanation:
Run your python script: python3 my_script.py
Detach stdin (so it can run independently): ... 0<&-
Redirect stderr to stdout so we can pipe them along together: ... 2>&1
Append output to some file but also keep the output going to stdout so we can pipe it someplace else: ... | tee -a ${OUTFILE} |
Pipe stdout to a netcat listening port so this machine can essentially "serve" the stdout from your python script: ... | nc -kl ${PORT}
Create a "double nested background subshell" this is explained in the link above but this will allow you to orphan "blah" so that it'll run even if your ssh connection ends (( ... blah ... &) &)
To view the stdout/stderr of my_script.py you now have several options. If you are still logged into that remote machine you can:
tail -f ${OUTFILE} # Same "OUTFILE" used in explanation component 4
nc localhost $PORT # Same "PORT" used in explanation component 5
If you are no longer logged in and you are now on a different machine (but on the same network) you can:
nc ${remote_machine} $PORT # Same "PORT" used in explanation component 5
Where ${remote_machine} is the hostname or IP address of the machine you ssh'ed into to run your command

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.

How to get the output of a telnet command from bash?

I'm trying to get the list of processes running on my Windows machine from Linux, but I don't get any output when I do it in a script. If I use telnet manually and use the command pslist I get the complete list of processes, but not in my script.
Here is the bash script (minus the variables):
( echo open ${host}
sleep 1
echo ${user}
sleep 3
echo ${pass}
sleep 1
echo pslist
sleep 2
) | telnet
and I simply call it with bash pslist.sh and the output is something like that:
telnet> Trying ip_address...
Connected to ip_address.
Escape character is '^]'.
Welcome to Microsoft Telnet Service
login: my_loginmy_passwordpslistConnection closed by foreign host.
What am I doing wrong ?
telnet is notoriously tricky to script. You may be able to succeed more often if you add a longer still sleep between the commands.
A better approach is to switch to a properly scriptable client, viz. netcat (aka nc). Better still would be to install an SSH server on your Windows box (perhaps for security only make it accessible from inside your network) and set it up with passwordless authentication. Then you can simply ssh user#ipaddress pslist
Terminate each echo with \r character, like this: echo -e "${user}\r"

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

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