How can I map a template to TCP?

I am trying to write a monitoring script. It should connect to some port on my server, read the output, and if the output is the expected value, type 1 otherwise 0.

I am working on a solution with cat < /dev/tcp/hostname/port, but the solution eludes me. Maybe something implying? I would prefer a bash script solution. Help rate!

+3
source share
6 answers

All other solutions use netcat to support the network, but you can end this if your bash is fairly recent and compiled with --enable-net-redirections(which, as far as I can tell, all but Debian and Ubuntu; feel free to comment if I have to configure).

Then grepcan do the actual testing. Its return code is a wrapper (0 for success, nonzero for failure), so you will need to invert this, but it bashhandles it just fine.

In a nutshell:

< /dev/tcp/host/port grep -q 'expected value'
echo $(( 1 - $? ))
+3
source

you can use netcat :

echo "GET /"|netcat google.com 80

and then output the output to script processing

+2
source
#!/bin/bash
EXPECTED="hello"
SERVER="example.com"
PORT="123"

netcat $SERVER $PORT | grep -F -q "$EXPECTED"

if [ $? ]; then
  echo 1
else
  echo 0
fi
+2

. . , , .

-, 80. , , , script , "" .

. gawk, , , gawk, . ( "" bash)

+1

. , (.. nc) . bash script .

:

#!/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 need to replace patternwith what you were looking for. This has the advantage of comparing each line, rather than the entire output of the command. I am not sure which is preferable in your case. I assume that you indicate expectthat you need a phased approach.

+1
source

Here is a script in the Bash shell that includes an HTTP request:

exec {stream}<>/dev/tcp/example.com/80
printf "GET / HTTP/1.1\nHost: example.com\nConnection: close\n\n" >&${stream}
grep Example <&${stream}
[ $? -eq 0 ] && echo Pattern match || echo Pattern not match

See also: Additional Information on Using Bash Built-in / dev / tcp File (TCP / IP) .

0
source

Source: https://habr.com/ru/post/1728590/


All Articles