EzDevInfo.com

netcat interview questions

Top netcat frequently asked interview questions

Emulating netcat -e

How can I emulate netcat -e with a version of netcat that does not have the -e option ?

I need to trigger a command remotely. I can do it with netcat - without -e:

#!/bin/bash

netcat -l 8080 ; myCommand.sh

That would do the trick, but I would like to reply to the client depending on the success or failure of the command (to have a kind of REST - like interface).

How could I do that ?

Thanks!


Source: (StackOverflow)

Netcat implementation in Python

I found this and am using it as my base, but it wasn't working right out of the box. My goal is also to treat it as a package instead of a command line utility, so my code changes will reflect that.

class Netcat:
    def __init__(self, hostname, port):
        self.hostname = hostname
        self.port = port
    def send(self, content):
    self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.socket.connect((self.hostname, self.port))
    self.socket.setblocking(0)
    result = '';
    read_ready, write_ready, in_error = select.select([self.socket], [], [self.socket], 5)
    if(self.socket.sendall(content) != None):
        return
    while(1):
        buffer = ''
        try:                
            buffer = self.socket.recv(128)
            while(buffer != ''):
                result += buffer
                try:
                    buffer = self.socket.recv(128)
                except socket.error as err:
                    print (err, type(err))
                    buffer = ''
            if(buffer == ''):
                break
        except socket.error as err:
            print (err, type(err))
        if(buffer == ''):
            break
    return result

When I send a basic command to my device, it returns the following.

50PMA-019 Connection Open
Atten #1 = 63dB

My code reads the first line, but then I get an error saying that the connection is temporarily unavailable and it does not get the second line. If I change it to blocking, it just blocks and never returns. Any thoughts?


Source: (StackOverflow)

Advertisements

How do I get netcat to accept connections from outside the LAN?

I'm using netcat as a backend to shovel data back and forth for a program I'm making. I tested my program on the local network, and once it worked I thought it would be a matter of simply forwarding a port from my router to have my program work over the internet. Alas! This seems not to be the case.

If I start netcat listening on port 6666 with:

nc -vv -l -p 6666,

then go to 127.0.0.1:6666 in a browser, as expected I see a HTTP GET request come through netcat (and my browser sits waiting in vain). If I go to my.external.ip.address:6666, however, nothing comes through at all and the browser displays 'could not connect to my.external.ip.address:6666'.

I know that the port is correctly forwarded, as www.canyouseeme.org says port 6666 is open (and when netcat is not listening, that its closed).

If I run netcat with -g my.adslmodem's.local.address to set the gateway address, I get the same behavior. Am I using this command line option correctly? Any insight as to what I'm doing wrong?


Source: (StackOverflow)

Send POST request with netcat

I have found this little script in PHP that send a simple request to twitter for update your status, I have tried this: http://pratham.name/twitter-php-script-without-curl.html, and it work. Now, I want send this request with netcat, but this doesn't work, why?

I send request in this way:

echo -e $head | nc twitter.com 80

The $head are my header that I have tried with also PHP, so it are right.

Anyone know how I can make this? Thanks to all.

edit.

head="POST http://twitter.com/statuses/update.json HTTP/1.1\r\n
Host: twitter.com\r\n
Authorization: Basic myname:passwordinbs64\r\n
Content-type: application/x-www-form-urlencoded\r\n
Content-length: 10\r\n
Connection: Close\r\n\r\n
status=mymessage";

echo -e $head | nc twitter.com 80

Source: (StackOverflow)

Scripting an HTTP header request with netcat

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.


Source: (StackOverflow)

Persistent connection in Bash script

I'm trying to create a persistent connection using bash. On terminal 1, I keep a netcat running as a server:

$ nc -vlkp 3000
Listening on [0.0.0.0] (family 0, port 3000)

On terminal 2, I create a fifo and keep a cat:

$ mkfifo fifo
$ cat > fifo

On terminal 3, I make the fifo as an input to a client netcat:

$ cat fifo | nc -v localhost 3000
Connection to localhost 3000 port [tcp/*] succeeded!

On terminal 4, I send whatever I want:

$ echo command1 > fifo
$ echo command2 > fifo
$ echo command3 > fifo

Going back to terminal 1, I see the commands being received:

$ nc -vlkp 3000
Listening on [0.0.0.0] (family 0, port 3000)
Connection from [127.0.0.1] port 3000 [tcp/*] accepted (family 2, sport 41722)
command1
command2
command3

So, everything works. But when I put that in a script (I called that fifo.sh), bash is not able to write into fifo:

On terminal 1, same listening server:

$ nc -vlkp 3000
Listening on [0.0.0.0] (family 0, port 3000)

On terminal 2, I run the script:

#!/bin/bash

rm -f fifo
mkfifo fifo
cat > fifo &
pid1=$!
cat fifo | nc -v localhost 3000 &
pid2=$!

echo sending...
echo comando1 > fifo
echo comando2 > fifo
echo comando3 > fifo

kill -9 $pid1 $pid2

The output in terminal 2 is:

$ ./fifo.sh 
Connection to localhost 3000 port [tcp/*] succeeded!
sending...

On terminal 1 I see only the connection. No commands:

$ nc -vlkp 3000
Listening on [0.0.0.0] (family 0, port 3000)
Connection from [127.0.0.1] port 3000 [tcp/*] accepted (family 2, sport 42191)
Connection closed, listening again.

Any idea on why it only works interactively? Or is there any other way to create a persistent connection using only Bash? I don't want to go for Expect because I have a bigger Bash script that does some work after sending the command1, and command2 depends on command1 output, etc.

Thank you!


Source: (StackOverflow)

Why does OS X allow listening on the same TCP port twice?

I was trying to debug port allocation problems in Jenkins on OS X by listening to certain ports with netcat, which led to some weird results.


In a terminal on OS X 10.8.2:

$ uname -rs
Darwin 12.2.1

$ nc -l 54321

Then in an second terminal:

$ nc -l 54321

And in a third terminal, lsof shows that both instances have bound to the same port:

$ lsof -i | grep 54321
nc  70706 chris    3u  IPv4 0x55618c024692f4d1      0t0  TCP *:54321 (LISTEN)
nc  70769 chris    3u  IPv4 0x55618c0232cb8661      0t0  TCP *:54321 (LISTEN)

On Linux:

First terminal:

$ uname -rs
Linux 3.2.0-34-generic

$ nc -l 54321

Second terminal:

$ nc -l 54321
nc: Address already in use

Why doesn't OS X also report that the address is already in use?


Source: (StackOverflow)

Using netcat/cat in a background shell script (How to avoid Stopped (tty input)? )

Abstract: How to run an interactive task in background?

Details: I am trying to run this simple script under ash shell (Busybox) as a background task.

myscript.sh&

However the script stops immediately...

[1]+ Stopped (tty input) myscript.sh

The myscript.sh contents... (only the relvant part, other then that I trap SIGINT, SIGHUP etc)

#!/bin/sh

catpid=0

START_COPY()
{
  cat /dev/charfile > /path/outfile &
  catpid = $! 
}

STOP_COPY()
{
  kill catpid 
}

netcat SOME_IP PORT | while read EVENT
do
  case $EVENT in
    start) START_COPY;;
    stop) STOP_COPY;;
  esac
done

From simple command line tests I found that bot cat and netcat try to read from tty. Note that this netcat version does not have -e to supress tty.

Now what can be done to avoid myscript becoming stopped?

Things I have tried so for without any success:

1) netcat/cat ... < /dev/tty (or the output of tty)

2) Running the block containing cat and netcat in a subshell using (). This may work but then how to grab PID of cat?

Over to you experts...


The problem still exists. A simple test for you all to try:

1) In one terminal run netcat -l -p 11111 (without &)

2) In another terminal run netcat localhost 11111 & (This should stop after a while with message Stopped (TTY input) )

How to avoid this?


Source: (StackOverflow)

How to purge connections left open by SSH ProxyCommand?

I have a webserver WWW1 and a front-facing proxy PRX. I use SSH ProxyCommand to connect to WWW1's internal IP (private IP) via PRX (private+public IP). For some connections (not all) I see a network connection left open after I'm finished. These add up!

~/.ssh/config

Host *
  ServerAliveInterval 5
  ControlMaster auto
  ControlPath ~/.ssh/master-%r@%h:%p

Host WWW1 WWW2 WWW3
  User foo
  ProxyCommand ssh -q -a -x PRX nc %h 22
  IdentityFile ~/.ssh/id_foo_WWWx

On PRX, lsof | grep WWW1:ssh shows 124 open connections at the moment. On WWW1, the same command shows 243 open connections. There are similar open connections for WWW2, WWW3 etc.

WWW1 and PRX are Debian. Client connections are coming from a mix of Debian, Ubuntu and OSX10.6. I use Emacs Tramp but this has no special configuration (AFAIK) outside of my ~/.ssh/config.

I'm concerned about running out of internal ports, and ideally I want these connections to clean themselves up without intervention. Ideally by configuring them to kill themselves off; failing that a command I can kill old processes with is fine!


Source: (StackOverflow)

nmap says port is closed while nestat says it's listening

This is Ubuntu 12.04 env. I have a TCP service running on port 8020 on the box:

My question is:

Why port 8020 is not discovered in nmap as an open port while nestat says it's listening?

if i run

netstat -tuplen

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       User           Inode       PID/Program name
tcp        0      0 127.0.0.1:9001          0.0.0.0:*               LISTEN      0          10564       1917/python    
tcp        0      0 127.0.0.1:8020          0.0.0.0:*               LISTEN      117        29259       4448/java       

But if i run

nmap -v -sT 127.0.0.1

Starting Nmap 5.21 ( http://nmap.org ) at 2012-08-10 08:51 PDT
Initiating Connect Scan at 08:51
Scanning localhost (127.0.0.1) [1000 ports]
Discovered open port 53/tcp on 127.0.0.1
Discovered open port 22/tcp on 127.0.0.1
Discovered open port 9000/tcp on 127.0.0.1
Discovered open port 631/tcp on 127.0.0.1
Discovered open port 9001/tcp on 127.0.0.1
Completed Connect Scan at 08:51, 0.04s elapsed (1000 total ports)
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00046s latency).
rDNS record for 127.0.0.1: hadoop-namenode-01
Not shown: 995 closed ports
PORT     STATE SERVICE
22/tcp   open  ssh
53/tcp   open  domain
631/tcp  open  ipp
9000/tcp open  cslistener
9001/tcp open  tor-orport

Read data files from: /usr/share/nmap
Nmap done: 1 IP address (1 host up) scanned in 0.10 seconds
       Raw packets sent: 0 (0B) | Rcvd: 0 (0B)

Source: (StackOverflow)

"ssh example.com" hangs but "ssh example.com bash -i" does not

everyday I encounter a very strange phenomenon.

From my university internet connection, sshing to my machine ("ssh example.com") works without any problems.

From my home adsl, "ssh example.com" my console gets stuck with this message:

debug1: Server accepts key: pkalg ssh-rsa blen 533
debug1: Enabling compression at level 6.
debug1: Authentication succeeded (publickey).
debug1: channel 0: new [client-session]
debug1: Requesting no-more-sessions@openssh.com
debug1: Entering interactive session.

Sometimes it might let me in but in most of the cases not. The funny thing is that if I execute "ssh example.com bash -i" I get logged in immediately.


Source: (StackOverflow)

Using netcat to send a UDP packet without binding

I am trying to use netcat to simulate a NAT traversal protocol.

I have one instance that is listening for UDP packets on port 6666, as so:

nc -ul 6666

In another terminal window, I am trying to periodically send a UDP packet from port 6666 (to open the return path on my router. this would be in a script that repeats every 20 seconds to re-open the port)

nc -u -p6666 mypinghost.com 4444

The problem is netcat fails on this ping call with the message:

nc: bind failed: Address already in use

Which implies that the listener having bound to port 6666 is blocking another process from sending from that port, or possibly that netcat is trying to bind to 6666 to listen.

Is this just how netcat is written, or can I tickle it some way to let me send a packet without binding to the port to listen?


Source: (StackOverflow)

linux script with netcat stops working after x hours

I've have to scripts:

#!/bin/bash

netcat -lk -p 12345 | while read line
do
    match=$(echo $line | grep -c 'Keep-Alive')
    if [ $match -eq 1 ]; then
        [start a command]
    fi
done

and

#!/bin/bash

netcat -lk -p 12346 | while read line
do
    match=$(echo $line | grep -c 'Keep-Alive')
    if [ $match -eq 1 ]; then
        [start a command]
    fi
done

I've put the two scripts in the '/etc/init.d/'

When I restart my Linux machine (RasbPi), both the scripts work fine.

I've tried them like 20 times, and they keep working fine.

But after around 12 hours, the whole system stops working. I've put in some loggin, but it seems that the scripts are not reacting anymore. But when I;

ps aux

I can see that the scripts are still running:

root      1686  0.0  0.2   2740  1184 ?        S    Aug12   0:00 /bin/bash /etc/init.d/script1.sh start
root      1689  0.0  0.1   2268   512 ?        S    Aug12   0:00 netcat -lk 12345
root      1690  0.0  0.1   2744   784 ?        S    Aug12   0:00 /bin/bash /etc/init.d/script1.sh start
root      1691  0.0  0.2   2740  1184 ?        S    Aug12   0:00 /bin/bash /etc/init.d/script2.sh start
root      1694  0.0  0.1   2268   512 ?        S    Aug12   0:00 netcat -lk 12346
root      1695  0.0  0.1   2744   784 ?        S    Aug12   0:00 /bin/bash /etc/init.d/script2.sh start

After a reboot they start working again... But thats a sin, rebooting a Linux machine periodically...

I've inserted some loggin, here's the outcome;

Listening on [0.0.0.0] (family 0, port 12345)
[2013-08-14 11:55:00] Starting loop.
[2013-08-14 11:55:00] Starting netcat.
netcat: Address already in use
[2013-08-14 11:55:00] Netcat has stopped or crashed.
[2013-08-14 11:49:52] Starting loop.
[2013-08-14 11:49:52] Starting netcat.
Listening on [0.0.0.0] (family 0, port 12345)
Connection from [16.8.94.19] port 12345 [tcp/*] accepted (family 2, sport 6333)
Connection closed, listening again.
Connection from [16.8.94.19] port 12345 [tcp/*] accepted (family 2, sport 6334)
[2013-08-14 12:40:02] Starting loop.
[2013-08-14 12:40:02] Starting netcat.
netcat: Address already in use
[2013-08-14 12:40:02] Netcat has stopped or crashed.
[2013-08-14 12:17:16] Starting loop.
[2013-08-14 12:17:16] Starting netcat.
Listening on [0.0.0.0] (family 0, port 12345)
Connection from [16.8.94.19] port 12345 [tcp/*] accepted (family 2, sport 6387)
Connection closed, listening again.
Connection from [16.8.94.19] port 12345 [tcp/*] accepted (family 2, sport 6388)
[2013-08-14 13:10:08] Starting loop.
[2013-08-14 13:10:08] Starting netcat.
netcat: Address already in use
[2013-08-14 13:10:08] Netcat has stopped or crashed.
[2013-08-14 12:17:16] Starting loop.
[2013-08-14 12:17:16] Starting netcat.
Listening on [0.0.0.0] (family 0, port 12345)
Connection from [16.8.94.19] port 12345 [tcp/*] accepted (family 2, sport 6167)
Connection closed, listening again.
Connection from [16.8.94.19] port 12345 [tcp/*] accepted (family 2, sport 6168)

Thanks


Source: (StackOverflow)

How can I close a netcat connection after a certain character is returned in the response?

We have a very simple tcp messaging script that cats some text to a server port which returns and displays a response.

The part of the script we care about looks something like this:

cat someFile | netcat somehost 1234

The response the server returns is 'complete' once we get a certain character code (specifically &001C) returned.

How can I close the connection when I receive this special character?

(Note: The server won't close the connection for me. While I currently just CTRL+C the script when I can tell it's done, I wish to be able to send many of these messages, one after the other.)

(Note: netcat -w x isn't good enough because I wish to push these messages through as fast as possible)


Source: (StackOverflow)

Strange behavoiur of netcat with UDP

I noticed a strange behaviour working with netcat and UDP. I start an instance (instance 1) of netcat that listens on a UDP port:

nc -lu -p 10000

So i launch another instance of netcat (instance 2) and try to send datagrams to my process:

nc -u 127.0.0.1 10000

I see the datagrams. But if i close instance 2 and relaunch again netcat (instance 3):

nc -u 127.0.0.1 10000

i can't see datagrams on instance 1's terminal. Obsiously the operating system assigns a different UDP source port at the instance 3 respect to instance 2 and the problem is there: if i use the same instance'2 source port (example 50000):

 nc -u -p 50000 127.0.0.1 10000

again the instance 1 of netcat receives the datagrams. UDP is a connection less protocol so, why? Is this a standard netcat behaviour?


Source: (StackOverflow)