/dev/tcp 监听而不是 nc 监听

h3r*_*ler 40 shell bash rhel io-redirection netcat

使用 netcat 侦听器,例如:

nc -l <port> < ~/.bashrc
Run Code Online (Sandbox Code Playgroud)

我可以在一台新机器(没有nc或 LDAP)上抓取我的 .bashrc :

cat < /dev/tcp/<ip>/<port> > ~/.bashrc
Run Code Online (Sandbox Code Playgroud)

我的问题是:有没有办法nc -l <port>用 /dev/tcp 而不是模仿我第一行中的功能nc

我正在使用的机器是极其坚固的实验室/沙盒环境 RHEL(没有 ssh,没有 nc,没有 LDAP,没有 yum,我无法安装新软件,而且它们没有连接到互联网)

Krz*_*ski 50

不幸的是,仅靠 bash 是不可能做到的。/dev/tcp/<ip>/<port>虚拟文件以 bash 尝试连接到指定<ip>:<port>usingconnect(2)函数的方式实现。为了创建监听套接字,它必须调用bind(2)函数。

您可以通过下载bash源代码并查看来检查这一点。它lib/sh/netopen.c_netopen4函数中的文件中实现(或 _netopen6,它也支持 IPv6)。这个函数被netopen同一个文件中的wrapper函数使用,它又直接在file redir.c( redir_special_openfunction)中使用来实现这个虚拟重定向。

您必须找到可以在您的机器上创建侦听套接字的其他应用程序。

  • 这就是 xinetd 的用途。它进行侦听,并为任何传入连接生成您的任意进程/脚本。有了它,任何东西都可以成为 TCP/IP 服务器。 (4认同)
  • @NahuelFouilleul:这并不完全正确。您可以使用所谓的“异步”或“事件驱动”网络编程(尝试使用谷歌搜索 select() 函数以及如何在网络编程中使用它),仅用一个线程/进程处理大量客户端。在许多情况下,它是接受大量客户的更好(更快)的方式。 (2认同)

Sté*_*las 26

如果安装了 Perl(就像在 RHEL 机器上一样):

perl -MIO::Socket::INET -ne 'BEGIN{$l=IO::Socket::INET->new(
  LocalPort=>1234,Proto=>"tcp",Listen=>5,ReuseAddr=>1);
  $l=$l->accept}print $l $_' < ~/.bashrc
Run Code Online (Sandbox Code Playgroud)

会起作用,除非本地防火墙不允许传入连接到 1234。

如果安装了 socat:

socat -u - tcp-listen:1234,reuseaddr < ~/.bashrc
Run Code Online (Sandbox Code Playgroud)

如果安装了 zsh:

zmodload zsh/net/tcp
ztcp -ld3 1234 && # start listening socket on fd 3
  ztcp -ad4 3 && # accept connection on fd 4
  ztcp -c 3 && # close the listening socket that is no longer needed
  cat < ~/.bashrc >&4 && # send the data
  ztcp -c 4 # close the communication socket to tell the other end we're finished
Run Code Online (Sandbox Code Playgroud)