一旦我找到了一个bash(或者可能是Perl;那是很久以前的事了,我对bash的了解还不足以区分一组象形文字和另一组象形文字)脚本,它可以通过网络连接lsof
或ps -aux
命令过滤打开的文件我认为它会定期更新域名解析。能够对打开的连接、打开的连接、关闭的连接有如此好的概述真是太好了。我通过某人的博客复制了它,但我怀疑他自己写了它,并且他自己只是复制了它并且只是传播它,因为它是在某些公共非商业许可下发布的。
您可能遇到过这个脚本,或者您知道 Ansatz 在 Bash 中写了类似的东西吗?
此致冯·斯波兹
答案1
这可能会满足您的需求:
#!/bin/sh
BASE=`basename "${0}" ".sh" `
TMP="/tmp/tmp.$$.${BASE}"
sudo lsof -Pni | grep '(ESTABLISHED)' >"${TMP}.connections"
#COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
#firefox 2713 username 88u IPv4 445702 0t0 TCP 192.168.0.10:42564->142.251.41.4:443 (ESTABLISHED)
#firefox 2713 username 94u IPv4 445943 0t0 TCP 192.168.0.10:50416->108.138.106.67:443 (ESTABLISHED)
#firefox 2713 username 119u IPv4 44675 0t0 TCP 192.168.0.10:49430->104.16.249.249:443 (ESTABLISHED)
#firefox 2713 username 158u IPv4 285032 0t0 TCP 192.168.0.10:57148->198.252.206.25:443 (ESTABLISHED)
#firefox 2713 username 256u IPv4 446322 0t0 TCP 192.168.0.10:53810->20.127.253.7:443 (ESTABLISHED)"
sudo lsof -Pi | grep '(ESTABLISHED)' >"${TMP}.connections"
#COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
#firefox 2317 username 80u IPv4 41156 0t0 TCP 192.168.0.10:37300->ec2-44-228-207-167.us-west-2.compute.amazonaws.com:443 (ESTABLISHED)
#firefox 2317 username 82u IPv4 244978 0t0 TCP 192.168.0.10:50412->239.237.117.34.bc.googleusercontent.com:443 (ESTABLISHED)
#firefox 2317 username 128u IPv4 173831 0t0 TCP 192.168.0.10:42774->stackoverflow.com:443 (ESTABLISHED)
#firefox 2317 username 129u IPv4 41121 0t0 TCP 192.168.0.10:47274->104.16.248.249:443 (ESTABLISHED)
#firefox 2317 username 136u IPv4 48202 0t0 TCP 192.168.0.10:35086->stackoverflow.com:443 (ESTABLISHED)
cat "${TMP}.connections" |
awk '{
#printf("/proc/%s/fd/1|%s|%s|%s\n", $2, $4, $9, $10 ) ;
printf("/proc/%s/mountinfo|%s|%s|%s\n", $2, $4, $9, $10 ) ;
}' |
while [ true ]
do
read line
if [ -z "${line}" ] ; then exit 0 ; fi
procpath=`echo "${line}" | awk -F \| '{ print $1 }' `
fd=`echo "${line}" | awk -F \| '{ print $2 }' `
conn=`echo "${line}" | awk -F \| '{ print $3 }' `
status=`echo "${line}" | awk -F \| '{ print $4 }' `
age=`stat "${procpath}" | grep '^Change' | awk '{ p=index( $3, "." ) ; time=substr( $3, 1, p-1 ) ; print $2, time ; }' `
dat=`awk -v FD="${fd}" '{ if( $4 == FD ){ print $0 ; exit } ; }' "${TMP}.connections" `
echo "${age} ${dat}"
done
输出看起来像这样:
2022-09-22 23:06:32 firefox 2317 username 80u IPv4 41156 0t0 TCP 192.168.0.10:37300->ec2-44-228-207-167.us-west-2.compute.amazonaws.com:443 (ESTABLISHED)
2022-09-22 23:06:32 firefox 2317 username 82u IPv4 244978 0t0 TCP 192.168.0.10:50412->239.237.117.34.bc.googleusercontent.com:443 (ESTABLISHED)
2022-09-22 23:06:32 firefox 2317 username 128u IPv4 173831 0t0 TCP 192.168.0.10:42774->stackoverflow.com:443 (ESTABLISHED)
2022-09-22 23:06:32 firefox 2317 username 129u IPv4 41121 0t0 TCP 192.168.0.10:47274->104.16.248.249:443 (ESTABLISHED)
2022-09-22 23:06:32 firefox 2317 username 136u IPv4 48202 0t0 TCP 192.168.0.10:35086->stackoverflow.com:443 (ESTABLISHED)
它侧重于开放连接,因为这些连接是主动与系统交互的连接。