Io-Redirection
如何從“>/dev/tcp/ip/port”中刪除“連接被拒絕”行
打開埠
user@linux:~$ >/dev/tcp/127.0.0.1/8080 && echo open || echo closed open user@linux:~$
封閉港口
user@linux:~$ >/dev/tcp/127.0.0.1/8088 && echo open || echo closed bash: connect: Connection refused bash: /dev/tcp/127.0.0.1/8088: Connection refused closed user@linux:~$
將 stderr 重定向到 /dev/null 不起作用
user@linux:~$ >/dev/tcp/127.0.0.1/8088 2>/dev/nul bash: connect: Connection refused bash: /dev/tcp/127.0.0.1/8088: Connection refused user@linux:~$
期望的輸出
user@linux:~$ >/dev/tcp/127.0.0.1/8088 && echo open || echo closed closed user@linux:~$
顛倒重定向的順序,讓我們
bash
知道 stderr 在 stdin 之前應該是什麼$ >/dev/tcp/127.0.0.1/8088 2>/dev/nul bash: connect: Connection refused bash: /dev/tcp/127.0.0.1/8088: Connection refused $ 2>/dev/null >/dev/tcp/127.0.0.1/8088 && echo open || echo closed closed $
第一個版本失敗的原因是重定向是按照它們出現的順序處理的,所以在
>/dev/tcp/127.0.0.1/8088 2>/dev/null
重定向到埠時,stderr 流還沒有被重定向。您可以使用實用程序在診斷輸出中清楚地看到相應的系統呼叫dup2()
以重定向 stderr(或在命令失敗的情況下缺少)strace
$ strace -e dup2,connect -f bash -c '>/dev/tcp/127.0.0.1/8088 2>/dev/null' connect(3, {sa_family=AF_INET, sin_port=htons(8088), sin_addr=inet_addr("127.0.0.1")}, 16) = -1 ECONNREFUSED (Connection refused) bash: connect: Connection refused bash: /dev/tcp/127.0.0.1/8088: Connection refused +++ exited with 1 +++ $ strace -e dup2,connect -f bash -c '2>/dev/null >/dev/tcp/127.0.0.1/8088 ' dup2(3, 2) = 2 connect(3, {sa_family=AF_INET, sin_port=htons(8088), sin_addr=inet_addr("127.0.0.1")}, 16) = -1 ECONNREFUSED (Connection refused) dup2(10, 2) = 2 +++ exited with 1 +++ $