프로세스별 사용하는 포트확인하는 쉘

특정서버에서 프로세스 별 사용하는 포트를 확인해야 했기에 처음으로 쉘 스크립트를 짜봤다..부끄러운 코드지만 추 후 쉘스크립트를 공부하고 돌아볼 용도로 업로드..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
unset process_info
unset process_id
unset program_name
unset local_address

rm -f sorttarget.txt

fileter_program_list=("java" "redis")

is_exist() {
local needle array value
needle="${1}"; shift; array=("${@}")
#for value in ${array[@]}; do [ ${value} == ${needle} ] && echo "true" && return; done
for value in ${array[@]};
do [[ "${needle}" == *"${value}"* ]] && echo "true" && return; done
echo "false"
}


netstat -nltp | while read line
do
process_info=`echo $line | cut -d ' ' -f7` # get PID/Program name

process_id=`echo $process_info | cut -d '/' -f1` # seprated by '/'
program_name=`echo $process_info | cut -d '/' -f2`
local_address=`echo $line | cut -d ' ' -f4`

# if [[ "$program_name" != *"java"* ]] && [[ "$program_name" != *"redis"* ]]; then
# continue
# fi

program_checker=`is_exist $program_name ${fileter_program_list[@]}`
if [ "${program_checker}" == "false" ]; then
continue
fi

echo $process_id " " $program_name " " $local_address " " >> sorttarget.txt
done

unset current_process_id
unset new_porcess_id
unset new_program_name
unset address_port
unset command

cat sorttarget.txt | sort -k 1 -t " " | while read line
do
new_process_id=`echo $line | cut -d ' ' -f1`
if [[ "$new_process_id" != "$current_process_id" ]]; then
printf "\n\n"
new_program_name=`echo $line | cut -d ' ' -f2`
echo "Pid/PName :" $new_process_id "/" $new_program_name
current_process_id=$new_process_id
ps -ef |grep $new_process_id | while read line
do
command=`echo $line | cut -d ' ' -f8`
if [[ "$command" == "grep" ]]; then
continue
fi
echo $line
break
done
fi

address_port=`echo $line | cut -d ' ' -f3`
echo " " $address_port
done
rm -f sorttarget.txt
Share