● 支持單獨查看CPU和內(nèi)存利用率,或網(wǎng)絡(luò)連接情況,或兩者皆可,name表示進程名,address表示網(wǎng)絡(luò)地址
● 支持輸出重定向,使用exec實現(xiàn)將標準輸出重定向到file文件,當(dāng)沒指定-o file選項參數(shù)時,則為標準輸出
● 支持設(shè)置刷新時間,當(dāng)沒指定-t seconds選項參數(shù)時,則默認為3秒
● 支持顯示多線程,當(dāng)指定-m選項時,則顯示多個線程的情況,默認不顯示
1
#! /bin/bash
2
#perf.sh
3
4
name=
5
address=
6
file=
7
seconds=
8
show_mthread=0
9
is_count=0
10
11
while getopts :p:n:o:t:mv opt
12
do
13
case $opt in
14
p) name=$OPTARG
15
;;
16
n) address=$OPTARG
17
;;
18
o) file=$OPTARG
19
;;
20
t) seconds=$OPTARG
21
;;
22
m) show_mthread=1
23
;;
24
v) is_count=1
25
;;
26
'?') echo "$0: invalid option -$OPTARG" >&2
27
echo "Usage: $0 [-p name] [-n address] [-o file] [-t seconds] [-m]" >&2
28
exit 1
29
;;
30
esac
31
done
32
33
shift $((OPTIND-1))
34
35
if [ -z "$name" -a -z "$address" ]; then
36
printf "Usage $(basename "$0") [-p name] [-n address] [-o file] [-t seconds] [-m]\nname or address must not be null\n"
37
exit 1
38
fi
39
40
if [ -z "$seconds" ]; then
41
seconds=3
42
fi
43
44
psflag="aux"
45
if [ "$show_mthread" = 1 ]; then
46
psflag="$psflag -T"
47
fi
48
49
psheader="`ps $psflag | head -n 1`"
50
sortflag="-k3nr -k4nr" #sort by descend order according to cpu and mem
51
52
netflag="-an --tcp --inet"
53
netheader="`netstat $netflag | head -n 2`"
54
is_exist=
55
56
show_process_info()
57
{
58
if [ -z "$1" ]; then
59
return 255
60
fi
61
62
result=`ps $psflag | grep -E "$1" | grep -E -v "gdb|grep|$0" | sort $sortflag`
63
if [ -z "$result" ]; then
64
is_exist=0
65
else
66
is_exist=1
67
uptime
68
echo "$psheader"
69
echo "$result"
70
fi
71
echo ""
72
}
73
74
show_net_connection()
75
{
76
if [ -z "$1" ]; then
77
return 255
78
fi
79
80
result=`netstat $netflag | grep -E $1`
81
if [ -n "$result" ]; then
82
echo "$netheader"
83
if [ "$is_count" = 1 ]; then
84
echo "$result" | awk '/^tcp/ { ++S[$NF] } END{ for(a in S) print a, S[a] }'
85
fi
86
fi
87
echo ""
88
}
89
90
tmpfile=`mktemp /tmp/per.XXXXXXXXXXXX`
91
92
while true
93
do
94
if [ -n "$file" ]; then
95
exec 1> $tmpfile
96
fi
97
98
show_process_info $name
99
show_net_connection $address
100
echo ""
101
102
sleep $seconds
103
104
if [ -n "$file" ]; then
105
exec 1>&-
106
107
if [ "$is_exist" = 1 ]; then
108
cat $tmpfile >> $file
109
fi
110
111
size=`ls -l $file | awk '{print $5}'`
112
if [ $size -ge $(expr 1024 \* 1024 \* 1) ]; then
113
cat /dev/null > $file
114
fi
115
else
116
clear
117
fi
118
done

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

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118
