Created
July 15, 2025 04:31
-
-
Save garenchan/09516fbcb14ce374f0a53d91569730a8 to your computer and use it in GitHub Desktop.
linux下查看进程连接的远程地址
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
PID=35339 # 替换为你的进程 PID | |
FD_DIR="/proc/${PID}/fd" | |
declare -A remote_addrs # 用于统计远程地址出现次数 | |
echo "🔍 正在分析进程 $PID 的所有 socket 连接..." | |
for fd in $(ls "$FD_DIR" 2>/dev/null); do | |
target=$(readlink "$FD_DIR/$fd" 2>/dev/null) | |
if [[ $target == socket:\[* ]]; then | |
# 修正:正确提取 socket inode 号码 | |
inode=$(echo "$target" | sed 's/socket:\[\(.*\)\]/\1/') | |
echo "FD $fd => Inode $inode" | |
# 查找对应的连接信息 | |
match=$(ss -eipn | grep -w "ino:${inode}") | |
if [[ -n "$match" ]]; then | |
echo "$match" | |
# 提取远程地址(如 192.168.1.1:80) | |
remote=$(echo "$match" | awk '{print $6}') | |
if [[ -n "$remote" ]]; then | |
((remote_addrs["$remote"]++)) | |
fi | |
else | |
echo "⚠️ 未找到该 inode 的连接信息。" | |
fi | |
echo "----------------------------------------" | |
fi | |
done | |
# 输出统计结果 | |
if [ ${#remote_addrs[@]} -eq 0 ]; then | |
echo "⚠️ 未找到任何远程连接。" | |
else | |
echo "📊 远程地址统计:" | |
for addr in "${!remote_addrs[@]}"; do | |
printf "%-25s %d 次\n" "$addr" "${remote_addrs[$addr]}" | |
done | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment