時間・CPU・MEM を抜き出して CSV 化。
- (環境によって若干違う可能性あるけど) 次のように出る。
op - 22:10:38 up 129 days, 5:32, 3 users, load average: 0.00, 0.00, 0.00
Tasks: 1 total, 0 running, 1 sleeping, 0 stopped, 0 zombie
Cpu(s): 0.0%us, 0.0%sy, 0.0%ni,100.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Mem: 1922436k total, 1855068k used, 67368k free, 149972k buffers
Swap: 2097144k total, 0k used, 2097144k free, 1531216k cached
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
10015 admin 20 0 112m 3536 1536 S 0.0 0.2 0:00.32 python
top - 22:10:39 up 129 days, 5:32, 3 users, load average: 0.00, 0.00, 0.00
Tasks: 1 total, 1 running, 0 sleeping, 0 stopped, 0 zombie
Cpu(s): 1.3%us, 1.3%sy, 0.0%ni, 97.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.3%st
Mem: 1922436k total, 1855192k used, 67244k free, 149972k buffers
Swap: 2097144k total, 0k used, 2097144k free, 1531240k cached
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
10015 admin 20 0 112m 3536 1536 R 4.0 0.2 0:00.36 python
top - 22:10:40 up 129 days, 5:32, 3 users, load average: 0.00, 0.00, 0.00
Tasks: 1 total, 0 running, 1 sleeping, 0 stopped, 0 zombie
Cpu(s): 0.7%us, 1.7%sy, 0.0%ni, 97.6%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Mem: 1922436k total, 1855316k used, 67120k free, 149972k buffers
Swap: 2097144k total, 0k used, 2097144k free, 1531240k cached
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
10015 admin 20 0 112m 3536 1536 S 4.0 0.2 0:00.40 python
- 今回は時間と CPU (%) と MEM (%) が必要だったので、正規表現とかで抜き出すスクリプトを作成。
- 以下、サンプル。入力ファイル名と出力ファイル名は決め打ち。
- エラー処理が無いので、top 出力のプロセスが消えた時点で落ちる。。
import csv
import re
'''
Top コマンドの出力ログを解析
'''
log_max = 10
time_log = 1
process_log = 8
process_cpu = 9
process_mem = 10
src_filename = "top_data.txt"
dest_filename = "log_analyze.txt"
r_timestamp = re.compile( "top - ([0-9:]+)" )
if __name__ == '__main__' :
f = open( src_filename )
lines = f.readlines()
f.close()
timestamp_list = []
cpu_list = []
mem_list = []
count = 0
for line in lines :
count += 1
line = line.rstrip()
if count % log_max == time_log :
print line
timestamp_list.append( r_timestamp.search( line ).group(1) )
if count % log_max == process_log :
print line
data = line.split( " " )
datum_count = 0
for datum in data :
if datum == "" :
continue
datum_count += 1
if datum_count == process_cpu :
cpu_list.append( datum )
elif datum_count == process_mem :
mem_list.append( datum )
dest = csv.writer( open( dest_filename, "w" ), lineterminator = "\n" )
for i in range( len( timestamp_list ) ) :
row = []
row.append( timestamp_list[i] )
row.append( cpu_list[i] )
row.append( mem_list[i] )
dest.writerow( row )
22:10:38,0.0,0.2
22:10:39,4.0,0.2
22:10:40,4.0,0.2
22:10:41,4.0,0.2
22:10:42,2.0,0.2
22:10:43,4.0,0.2
22:10:44,3.0,0.2
22:10:45,4.0,0.2
22:10:46,5.0,0.2
22:10:47,4.0,0.2
22:10:48,4.0,0.2
22:10:49,4.0,0.2
...