I'm trying to play around with netcat to learn more about how HTTP works. I'd like to script some of it in bash or Perl, but I've hit upon a stumbling block early on in my testing.
If I run netcat straight from the prompt and type in a HEAD request, it works and I receive the headers for the web server I'm probing.
This works:
[romandas#localhost ~]$ nc 10.1.1.2 80
HEAD / HTTP/1.0
HTTP/1.1 200 OK
MIME-Version: 1.0
Server: Edited out
Content-length: 0
Cache-Control: public
Expires: Sat, 01 Jan 2050 18:00:00 GMT
[romandas#localhost ~]$
But when I put the same information into a text file and feed it to netcat through a pipe or via redirection, in preparation for scripting, it doesn't return the headers.
The text file consists of the HEAD request and two newlines:
HEAD / HTTP/1.0
Sending the same information via echo or printf doesn't work either.
$ printf "HEAD / HTTP/1.0\r\n"; |nc -n 10.1.1.2 80
$ /bin/echo -ne 'HEAD / HTTP/1.0\n\n' |nc 10.1.1.2 80
Any ideas what I'm doing wrong? Not sure if it's a bash problem, an echo problem, or a netcat problem.
I checked the traffic via Wireshark, and the successful request (manually typed) sends the trailing newline in a second packet, whereas the echo, printf, and text file methods keep the newline in the same packet, but I'm not sure what causes this behavior.
You need two lots of "\r\n", and also to tell netcat to wait for a response. printf "HEAD / HTTP/1.0\r\n\r\n" |nc -n -i 1 10.1.1.2 80 or similar should work.
Another way is to use what is called the 'heredoc' convention.
$ nc -n -i 1 10.1.1.2 80 <<EOF
> HEAD / HTTP/1.0
>
> EOF
Another way to get nc to wait for the response is to add a sleep to the input. e.g.
(printf 'GET / HTTP/1.0\r\n\r\n'; sleep 1) | nc HOST 80
You can use below netcat command to make your instance webserver:
MYIP=$(ifconfig eth0|grep 'inet addr'|awk -F: '{print $2}'| awk '{print $1}')
while true; do echo -e "HTTP/1.0 200 OK\r\n\r\nWelcome to $MYIP" | sudo nc -l -p 80 ; done&
This line will also work as equivalent:
echo -e "HEAD / HTTP/1.1\nHost: 10.1.1.2\nConnection: close\n\n\n\n" | netcat 10.1.1.2 80
Related
I just started using ncat, and playing around with simple HTTP requests, I came across the following:
Starting ncat and typing a two-line get request works fine:
$ ncat 192.168.56.20 80
GET / HTTP/1.1
Host: 192.168.56.20
HTTP/1.1 200 OK
If however the request gets echoed to ncat, it apparently breaks somewhere:
$ echo 'GET / HTTP/1.1\nHost: 192.168.56.20' | ncat 192.168.56.20 80
HTTP/1.1 400 Bad Request
I don't get it.
The \n in the string is sent literally. Use echo -e to enable interpretation of backslash escapes. Also, the newline sequence for HTTP 1.1 is \r\n (CRLF). And the header section ends with an additional end-of-line.
Try:
echo -e 'GET / HTTP/1.1\r\nHost: 192.168.56.20\r\n\r\n' | ncat 192.168.56.20 80
Alternatively, the ncat has the option to convert new lines to CRLF:
-C, --crlf Use CRLF for EOL sequence
Hence, you can write:
echo -e 'GET / HTTP/1.1\nHost: 192.168.56.20\n\n' | ncat -C 192.168.56.20 80
and you should get the same result.
I need to get a nonce from a http service
I am using curl and later openssl to calculate the sha1 of that nonce.
but for that i need to get the nonce to a variable
1 step (done)
curl --user username:password -v -i -X POST http://192.168.0.202:8080/RPC3 -o output.txt -d #initial.txt
and now, the output file #output.txt holds the http reponse
HTTP/1.1 401 Unauthorized
Server: WinREST HTTP Server/1.0
Connection: Keep-Alive
Content-Length: 89
WWW-Authenticate: ServiceAuth realm="WinREST", nonce="/wcUEQOqUEoS64zKDHEUgg=="
<html><head><title>Unauthorized</title></head><body>Error 401: Unauthorized</body></html>
I have to get the position of "nonce=" and extract all the way to the " char.
How can I get in bash, the value of nonce ??
Regards
Pretty simple with grep using the -o/--only-matching and -P/--perl-regexp options (available in GNU grep):
$ grep -oP 'nonce="\K[^"]+' output.txt
/wcUEQOqUEoS64zKDHEUgg==
The -o option will print only matched part, which would normally include nonce=" if we had not used the reset match start escape sequence available in PCRE.
Additionally, if your output.txt (i.e. server response) can contain more than one nonce, and you are interested in only reading the first one, you can use the -m1 option (as Glenn suggests):
$ grep -oPm1 'nonce="\K[^"]+' output.txt
To store that nonce in a variable, simply use command substitution; or just pass it through openssl sha1 to get that digest you need:
$ nonce=$(grep -oPm1 'nonce="\K[^"]+' output.txt)
$ echo "$nonce"
/wcUEQOqUEoS64zKDHEUgg==
$ read hash _ <<<"$(grep -oPm1 'nonce="\K[^"]+' output.txt | openssl sha1 -r)"
$ echo "$hash"
2277ef32822c37b5c2b1018954f750163148edea
You can use GNU sed for this as below :
ubuntu$ cat output.txt
HTTP/1.1 401 Unauthorized
Server: WinREST HTTP Server/1.0
Connection: Keep-Alive
Content-Length: 89
WWW-Authenticate: ServiceAuth realm="WinREST", nonce="/wcUEQOqUEoS64zKDHEUgg=="
<html><head><title>Unauthorized</title></head><body>Error 401: Unauthorized</body></html>
ubuntu$ sed -E -n 's/(.*)(nonce="\/)([a-zA-Z0-9=]+)(")(.*)/\3/gp' output.txt
wcUEQOqUEoS64zKDHEUgg==
Regards!
Log file contains this line.
Nov 28 21:39:25 soft-server sshd[11946]: Accepted password for myusername from 10.0.2.2 port 13494 ssh2
I want to run the curl command only if the log file contains the string "Accepted password for" and append the IP address to URL.
Something like this:
if [ grep -q "Accepted password for" var/log/auth.log]
then
curl 'www.examplestextmessage.com/send-a-message/text=$IP_address'
fi
Additionally, how to rewrite the above script which can check multiple logins and to run separate curl commands for each results?
for eg:
Nov 28 21:35:25 localhost sshd[565]: Server listening on 0.0.0.0 port 22
Nov 28 21:39:25 soft-server sshd[11946]: Accepted password for myusername
from 10.0.2.2 port 13494 ssh2
Nov 28 21:40:25 localhost sshd[565]: Server listening on 0.0.0.0 port 22
Nov 28 21:41:25 localhost sshd[565]: Server listening on 0.0.0.0 port 22
Nov 28 21:42:25 localhost sshd[565]: Server listening on 0.0.0.0 port 22
Nov 28 21:43:25 soft-server sshd[11946]: Accepted password for myusername from 10.0.1.1 port 13494 ssh2
grep -oP 'Accepted password for \w+ from\s\K[^ ]+' log.file|while read line;
do
curl "www.examplestextmessage.com/send-a-message/text=$line"
done
Explanation:
First grep will list the IP addresses from the line containing the words "Accepted password for". Then the stream of grep result is feeded into while loop to append ip addresses to curl and execute curl.
1 line script with xargs:
grep -oP 'Accepted password for \w+ from\s\K[^ ]+' "/var/log/auth.log" | xargs -I{} -r curl -v -L "www.examplestextmessage.com/send-a-message/text={}"
xarg -r If the standard input is completely empty, do not run the command. By default, the command is run once even if there is no input.
xarg -I{} option changes the way the new command lines are built. Instead of adding as many arguments as possible at a time, xargs will take one name at a time from its input, look for the given token ({} here) and replace that with the name.
Explanation :
grep the content "Accepted password for"
From result set find ip address using awk/cut
use IP address list as input for loop
below is code example
for IP_address in `cat auth.log | grep 'Accepted password for' | awk '{print $11}'`
do
curl "www.examplestextmessage.com/send-a-message/text=$IP_address"
done
Another option for completeness is sed using -E to cater for regular expressions:
sed -En 's/(^.*Accepted password for )(.*)( from )(.*)( port.*$)/\4/p'
This will split the text into five separate sections signified by extracts in between brackets. We then focus on the 4th extract to get the ip address
host unix.stackexchange.com at the command line, gives you the following results:
unix.stackexchange.com has address 198.252.206.140
I would like to use this command in a bash script that will read hostname.txt which has multiple hostnames listed like so:
server1
server2
server3
server4
server5
I would then like it to either output results to screen or another txt file.
Here is simple code snippet that does what you ask for:
cat hostname.txt | while read line
do
host $line | grep ' address '
done >output.txt
Remove the grep filter if you want all the output, it's just there to match what you requested in your question.
Here's a code snippet that saved as a script and made executable will produce the output you requested. I added piping | the output through grep to filter out other output from host that can occur.
cat hostname.txt | while read line; do
x="$(host "$line")"
echo "$x" | grep 'address'
done
Say the hostname.txt file contains:
google.com
yahoo.com
stackoverflow.com
The output as written will be:
google.com has address 216.58.219.142
google.com has IPv6 address 2607:f8b0:4008:808::200e
yahoo.com has address 98.138.253.109
yahoo.com has address 206.190.36.45
yahoo.com has address 98.139.183.24
stackoverflow.com has address 198.252.206.140
Without piping | the output through grep it's:
google.com has address 216.58.219.142
google.com has IPv6 address 2607:f8b0:4008:808::200e
google.com mail is handled by 20 alt1.aspmx.l.google.com.
google.com mail is handled by 10 aspmx.l.google.com.
google.com mail is handled by 40 alt3.aspmx.l.google.com.
google.com mail is handled by 30 alt2.aspmx.l.google.com.
google.com mail is handled by 50 alt4.aspmx.l.google.com.
yahoo.com has address 206.190.36.45
yahoo.com has address 98.139.183.24
yahoo.com has address 98.138.253.109
yahoo.com mail is handled by 1 mta5.am0.yahoodns.net.
yahoo.com mail is handled by 1 mta7.am0.yahoodns.net.
yahoo.com mail is handled by 1 mta6.am0.yahoodns.net.
stackoverflow.com has address 198.252.206.140
stackoverflow.com mail is handled by 10 aspmx2.googlemail.com.
stackoverflow.com mail is handled by 5 alt1.aspmx.l.google.com.
stackoverflow.com mail is handled by 1 aspmx.l.google.com.
stackoverflow.com mail is handled by 5 alt2.aspmx.l.google.com.
stackoverflow.com mail is handled by 10 aspmx3.googlemail.com.
When executing the script you can redirect the output by e.g.:
scriptname > output.txt
You can change cat hostname.txt to cat $# to then use the script, e.g:
scriptname hostname.txt
Or:
scriptname hostname.txt > output.txt
I'm trying to send a file, line by line, with the following commands:
nc host port < textfile
cat textfile | nc host port
I've tried with tail and head, but with the same result: the entire file is sent as a unique line.
The server is listening with a specific daemon to receive data log information.
I'd like to send and receive the lines one by one, not the whole file in a single shot.
How can I do that?
Do you HAVE TO use netcat?
cat textfile > /dev/tcp/HOST/PORT
can also serve your purpose, at least with bash.
I'de like to send, and receive, one by one the lines, not all the file in a single shot.
Try
while read x; do echo "$x" | nc host port; done < textfile
OP was unclear on whether they needed a new connection for each line. But based on the OP's comment here, I think their need is different than mine. However, Google sends people with my need here so here is where I will place this alternative.
I have a need to send a file line by line over a single connection. Basically, it's a "slow" cat. (This will be a common need for many "conversational" protocols.)
If I try to cat an email message to nc I get an error because the server can't have a "conversation" with me.
$ cat email_msg.txt | nc localhost 25
554 SMTP synchronization error
Now if I insert a slowcat into the pipe, I get the email.
$ function slowcat(){ while read; do sleep .05; echo "$REPLY"; done; }
$ cat email_msg.txt | slowcat | nc localhost 25
220 et3 ESMTP Exim 4.89 Fri, 27 Oct 2017 06:18:14 +0000
250 et3 Hello localhost [::1]
250 OK
250 Accepted
354 Enter message, ending with "." on a line by itself
250 OK id=1e7xyA-0000m6-VR
221 et3 closing connection
The email_msg.txt looks like this:
$ cat email_msg.txt
HELO localhost
MAIL FROM:<system#example.com>
RCPT TO:<bbronosky#example.com>
DATA
From: [IES] <system#example.com>
To: <bbronosky#example.com>
Date: Fri, 27 Oct 2017 06:14:11 +0000
Subject: Test Message
Hi there! This is supposed to be a real email...
Have a good day!
-- System
.
QUIT
Use stdbuf -oL to adjust standard output stream buffering. If MODE is 'L' the corresponding stream will be line buffered:
stdbuf -oL cat textfile | nc host port
Just guessing here, but you probably CR-NL end of lines:
sed $'s/$/\r/' textfile | nc host port