Linux

在 linux 上,有沒有辦法記錄程序嘗試通信的埠?

  • August 25, 2020

問題:我正在嘗試確定為特定程序打開哪些埠

我有許多程序需要訪問遠端主機上的服務,但我不知道它們試圖使用哪些埠來達到此目的。我不想將防火牆打開到0-1024(或0-65k),而是想確定程序在執行時使用的埠。

要檢查的第一個程序是kinit. 從我收集的文件中,我需要88為入站 udp 流量打開埠,88為出站 tcp 和 udp 流量打開埠。但這似乎還不夠,因為程序會響應

kinit: Resource temporarily unavailable while getting initial credentials

打開所有埠會產生正確的身份驗證流程kinit

Using default cache: /tmp/krb5cc_16381
Using principal: *****@******.******.***
Password for *****@******.******.***:
Authenticated to Kerberos v5

我知道如何使用lsofnetstat以及ss檢索綁定到埠的時間較長的程序的開放埠,但尤其是kinit似乎避開了這個列表,即使與諸如watch.

編輯:接受的答案立即向我展示了罪魁禍首:DNS;

strace -e trace=connect kinit <user>@<kdc>
connect(3, {sa_family=AF_UNIX, sun_path="/var/run/nscd/socket"}, 110) = -1 ENOENT (No such file or directory)
connect(3, {sa_family=AF_UNIX, sun_path="/var/run/nscd/socket"}, 110) = -1 ENOENT (No such file or directory)
connect(3, {sa_family=AF_INET, sin_port=htons(53), sin_addr=inet_addr("<kdc_ip>")}, 16) = 0

打開此埠修復了 Kerberos 的問題

你可以試試 strace:

strace -e trace=connect your_program with arguments

這是一個範例輸出:

$ strace -e trace=connect ssh somehost -p 8081
connect(3, {sa_family=AF_LOCAL, sun_path="/var/run/nscd/socket"}, 110) = -1 ENOENT (No such file or directory)
connect(3, {sa_family=AF_LOCAL, sun_path="/var/run/nscd/socket"}, 110) = -1 ENOENT (No such file or directory)
connect(3, {sa_family=AF_LOCAL, sun_path="/var/run/nscd/socket"}, 110) = -1 ENOENT (No such file or directory)
connect(3, {sa_family=AF_LOCAL, sun_path="/var/run/nscd/socket"}, 110) = -1 ENOENT (No such file or directory)
connect(3, {sa_family=AF_INET, sin_port=htons(53), sin_addr=inet_addr("127.0.1.1")}, 16) = 0
connect(3, {sa_family=AF_INET, sin_port=htons(8081), sin_addr=inet_addr(<host ip address>)}, 16) = 0
connect(4, {sa_family=AF_LOCAL, sun_path="/run/user/1000/keyring/ssh"}, 110) = 0

您需要的行是帶有sa_family=AF_INET.

引用自:https://serverfault.com/questions/1031270