2015年2月7日 星期六

nc — arbitrary TCP and UDP connections and listens


幾乎任何使用 TCP,UDP或UNIX-domain socket的動作都可以用nc來達成,常見的功能如。
  • simple TCP proxies
  • shell-script based HTTP clients and servers
  • network daemon testing
  • a SOCKS or HTTP ProxyCommand for ssh(1)
  • and much, much more


SYNOPSIS
     nc [-46bCDdhklnrStUuvZz] [-I length] [-i interval] [-O length]
        [-P proxy_username] [-p source_port]
        [-q seconds] [-s source] [-T toskeyword] [-V rtable]
        [-w timeout] [-X proxy_protocol] [-x proxy_address[:port]]
        [destination] [port]


options: -v, verbose

不加-v,發生錯誤時不會有訊息。
brook@vista:~$ nc 127.0.0.1 12345
brook@vista:~$ nc -v 127.0.0.1 12345
nc: connect to 127.0.0.1 port 12345 (tcp) failed: Connection refused
brook@vista:~$ nc -v 127.0.0.1 80
Connection to 127.0.0.1 80 port [tcp/http] succeeded!
輸入GET / HTTP/1.1
輸入HOST: 127.0.0.1
輸入[enter]
輸入[enter]

HTTP/1.1 200 OK
Date: Tue, 27 Jan 2015 08:24:17 GMT
Server: Apache/2.2.22 (Ubuntu)
Last-Modified: Mon, 23 Dec 2013 04:13:45 GMT
ETag: "1b806ff-b1-4ee2bdaa24ac8"
Accept-Ranges: bytes
Content-Length: 177
Vary: Accept-Encoding
Content-Type: text/html
X-Pad: avoid browser bug

<html><body><h1>It works!</h1>
<p>This is the default web page for this server.</p>
<p>The web server software is running but no content has been added, yet.</p>
</body></html>


options: -l, listen for an incoming connection rather than initiate a connection to a remote host

等同開socket在listen,預設是tcp。
brook@vista:~$ nc -l 127.0.0.1 5000 -> server
brook@vista:~$ netstat -nal | grep 5000
tcp        0      0 127.0.0.1:5000          0.0.0.0:*               LISTEN
brook@vista:~$ nc 127.0.0.1 5000 -> client


options: -u, Use UDP instead of the default option of TCP.

使用UDP取代預設的TCP
brook@vista:~$ nc -lu 127.0.0.1 5000 -> server
brook@vista:~$ nc -u 127.0.0.1 5000 -> client


使用nc當Web Server

{ echo -ne "HTTP/1.0 200 OK\r\nContent-Length: $(wc -c < some.file)\r\n\r\n"; cat some.file; } | nc -l 5050
開啟Browser,http://127.0.0.1:5050/,就可以看到網頁了。

Works as a Port Scanner

brook@vista:~$ nc -v -z 127.0.0.1 80-200 2>&1 | grep -v failed
Connection to 127.0.0.1 80 port [tcp/http] succeeded!
Connection to 127.0.0.1 139 port [tcp/netbios-ssn] succeeded!


Transfering Files

sender
brook@vista:~$ md5sum usb_eth.txt
2367562f85f99fe972b9d6a83ce38099  usb_eth.txt
brook@vista:~$ tar cvf - usb_eth.txt | nc 127.0.0.1 5000
usb_eth.txt

receiver
brook@vista:/tmp$ nc -l 5000 | tar xvf -
usb_eth.txt
brook@vista:/tmp$ md5sum usb_eth.txt
2367562f85f99fe972b9d6a83ce38099  usb_eth.txt


Git Proxy

以下的Script是我拿用當gitproxy用的
#!/bin/bash
# http://tech-tacolin.blogspot.tw/2013/04/git-http-proxy.html
PROXY=1.2.3.4
PROXYPORT=3128
case $1 in
    192.168.1.1 | internal-ip)
        nc -X connect $*
        ;;
    *)
        nc -x $PROXY:$PROXYPORT -X connect $*
        ;;
esac


    參考資料
  1. Netcat WIKI
  2. Netcat(Linux nc 指令)網路管理者工具實用範例



1 則留言:

熱門文章