获取pid
squid2pid=`ps -ef |grep squid2 | grep -v grep | awk '{print $2}'`
squid2pid=`lsof -n -P -i:82|awk '{print $2}'|grep -v PID`
======================
http://blog.ailms.me/2014/05/25/find-listen-port-by-pid-without-with-lsof-or-ss-or-netstat.html
如何根据 pid 找到该进程打开的端口 (不使用 lsof、ss、netstat)
short answer :通过 /proc/net/tcp 和 /proc/net/udp 即可
1
2
3
|
root@wordpress:/proc/3464/fd# pidof nginx
25115 25114 25113 25112 25111 25110 25109 25108 25107 3470
root@wordpress:/proc/3464/fd#
|
# 找到 pid
1
|
list=$(pidof nginx)
|
# 找到所有相关的 socket 和 indoe ([]里面的数值)
1
2
3
4
5
|
root@wordpress:~# eval find -L /proc/{${list// /,}}/fd -type s | xargs -i readlink -f {}
/proc/25115/fd/socket:[18530361]
/proc/25115/fd/socket:[18530363]
/proc/25115/fd/socket:[18530365]
(more)
|
# 提出 inode
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
root@wordpress:~# eval find -L /proc/{${list// /,}}/fd -type s | xargs -i readlink -f {} | awk -F'[][]' '{print $2}' | sort -u
13802
18530361
18530362
18530363
18530364
18530365
18530366
18530367
18530368
18530369
18530370
18530371
18530372
18530373
18530374
18530375
18530376
18530377
18530378
root@wordpress:~#
|
# 查找 /proc/net/tcp,udp (假设不关心 unix socket),查到匹配的 inode 的行,并提取其中的 local-addr:local-port 部分
# 这里不是很严谨,egrep 不是很合适,应该是用 awk 逐个比较 $2 是否相等
1
2
3
|
root@wordpress:~# egrep -w -f <(echo "$inodes") /proc/net/tcp /proc/net/udp -h | awk '{print $2}'
00000000:0050
root@wordpress:~#
|
# 最后翻译为ip:port
1
2
3
4
5
6
7
|
root@wordpress:~# echo $((16#$(echo $ipPort | cut -d ':' -f 2)))
80
root@wordpress:~#
root@wordpress:~# echo $ipPort | cut -d ':' -f 1 | sed 's/../&\n/g' | tac | xargs -i printf "%d." 0x{} | sed 's/.$/\n/'
0.0.0.0
root@wordpress:~#
|
综合起来脚本是 (没有区分是 tcp 还是 udp ,如果要区分,分开2次 for 循环即可)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
list=$(pidof $proc)
inodes=$(eval find -L /proc/{${list// /,}}/fd -type s | xargs -i readlink -f {} | awk -F'[][]' '{print $2}' | sort -u)
ipPortPairs=$(egrep -w -f <(echo "$inodes") /proc/net/tcp /proc/net/udp -h | awk '{print $2}')
for line in $ipPortPairs ; do
port=$(echo $((16#$(echo $line | cut -d ':' -f 2) )) )
ip=$(echo $line | cut -d ':' -f 1 | sed 's/../&\n/g' | tac | xargs -i printf "%d." 0x{} | sed 's/.$/\n/')
echo "$ip:$port"
done
|