I'm trying to write a monitoring script. It should connect to some port on my server. Read the output. If the output is the expected value, print 1, otherwise print 0. I'm working on a solution involving cat < /dev/tcp/hostname/port
, but the solution eludes me. Maybe something involving expect? Prefer a bash script solution. Help appreciated!
views:
376answers:
4there are little examples here. you can take reference to it. However, you should note that it also depends on what services runs on your port and what protocol it speaks.
if you are connecting to web server, common port is 80. But if you running your own application running as a server, make sure your script knows how to "talk" to each other.
another resource you can look at here. Its gawk though, so if you have gawk, then you may want to try it. (you can "port" to bash too)
#!/bin/bash
EXPECTED="hello"
SERVER="example.com"
PORT="123"
COUNT=`netcat $SERVER $PORT | grep -F -c $EXPECTED`
if [ $COUNT -eq 0 ]; then
print 0
else
print 1
fi
I would suggest you use a popen approach. That way you can read with whatever command you like (i.e. nc
) and handle the output iteratively. This can all be spawned by a bash script if necessary.
For example:
#!/usr/bin/env ruby
IO.popen("nc host 4560") do |stdout|
while line = stdout.gets
if line =~ /pattern/
puts "1"
else
puts "0"
end
end
end
Obviously you would need to substitute pattern
with whatever you were looking for. This has the advantage of comparing each line instead of the entire output of the command. I'm not sure which is preferable in your case. I assume from you mentioning expect
that you want a line-by-line approach.