netcat 是一款调试 TCP/UDP 网络连接的利器,常被称作网络调试的瑞士军刀,可见其功能强大。 netcat 在 Linux, Windows 等各大操作系统上都有对应等发行版,以下以 Linux(Ubuntu 16.04) 为例介绍其几个强大的用法。 ![wKiom1idqMihhTdoAABux5ZXWF0191.png-wh_651x-s_657031727.png][1] netcat 在 Linux 中一般通过命令 nc 调用。我们先来看下它的帮助文档 ``` # nc -h OpenBSD netcat (Debian patchlevel 1.105-7ubuntu1) This is nc from the netcat-openbsd package. An alternative nc is available in the netcat-traditional package. usage: nc [-46bCDdhjklnrStUuvZz] [-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] Command Summary: -4 Use IPv4 -6 Use IPv6 -b Allow broadcast -C Send CRLF as line-ending -D Enable the debug socket option -d Detach from stdin -h This help text -I length TCP receive buffer length -i secs Delay interval for lines sent, ports scanned -j Use jumbo frame -k Keep inbound sockets open for multiple connects -l Listen mode, for inbound connects -n Suppress name/port resolutions -O length TCP send buffer length -P proxyuser Username for proxy authentication -p port Specify local port for remote connects -q secs quit after EOF on stdin and delay of secs -r Randomize remote ports -S Enable the TCP MD5 signature option -s addr Local source address -T toskeyword Set IP Type of Service -t Answer TELNET negotiation -U Use UNIX domain socket -u UDP mode -V rtable Specify alternate routing table -v Verbose -w secs Timeout for connects and final net reads -X proto Proxy protocol: "4", "5" (SOCKS) or "connect" -x addr[:port] Specify proxy address and port -Z DCCP mode -z Zero-I/O mode [used for scanning] Port numbers can be individual or ranges: lo-hi [inclusive] ``` 可以看到我们使用的是 `netcat-openbsd` 这个发行版的 netcat, 除此之外,还有 `netcat-traditiona`l 等发行版。不同发行版的基本功能相同,只是有细微的差别。 ![011659z6zs4uu5s5jd4s5j.gif][2] 简单来说, nc 有以下功能: - 模拟 TCP 服务端 - 模拟 TCP 客户端 - 模拟 UDP 服务端 - 模拟 UDP 客户端 - 模拟 UNIX socket 服务端 - 模拟 UNIX socket 客户端 - 端口扫描 - 传输文件 - 将服务器 bash 暴露给远程客户端 - 内网穿透,反向获取防火墙后的机器的 bash 以下分别举例说明。 ##实例环境设定 假设 - 服务器 A 有外网 IP 202.118.69.40 - 服务器 B 没有外网 IP - 客户端 C 有外网 IP 202.119.70.41 三台主机上均为 Ubuntu 16.04 操作系统。 ## 1、模拟 TCP 服务端 `nc -lk 9090` 在服务器 A 执行以上命令,将会把 nc 绑定到 9090 端口,并开始监听请求。 - `-l` 代表 netcat 将以监听模式运行; - `-k` 表示 nc 在接收完一个请求后不会立即退出,而是会继续监听其他请求。 这时就可以请求该接口了, nc 会把请求报文输出到标准输出。 例如在客户端 C 执行 `curl 202.118.69.40` nc 将会将 HTTP 请求的报文输出到标准输出 ``` GET / HTTP/1.1 Host: 192.168.0.71:9090 User-Agent: curl/7.54.0 Accept: */* ``` ## 2、模拟 TCP 客户端 `printf "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n" | nc example.com 80` 在客户端 C 执行上述代码, C 的输出如下 ``` Connection to example.com port 80 [tcp/http] succeeded! HTTP/1.1 200 OK Accept-Ranges: bytes Cache-Control: max-age=604800 Content-Type: text/html; charset=UTF-8 Date: Tue, 09 Oct 2018 07:08:38 GMT Etag: "1541025663+gzip" Expires: Tue, 16 Oct 2018 07:08:38 GMT Last-Modified: Fri, 09 Aug 2013 23:54:35 GMT Server: ECS (sjc/4E52) Vary: Accept-Encoding X-Cache: HIT Content-Length: 1270 Example Domain 文章目录