由於一些原因,需要SAE上站點的日志文件,從SAE上只能按天下載,下載下來手動處理比較蛋疼,尤其是數量很大的時候。還好SAE提供了API可以批量獲得日志文件下載地址,剛剛寫了python腳本自動下載和合並這些文件
文檔位置在這裡
請求中需要設置的變量如下
api_url = 'http://dloadcenter.sae.sina.com.cn/interapi.php?'
appname = 'xxxxx'
from_date = '20140101'
to_date = '20140116'
url_type = 'http' # http|taskqueue|cron|mail|rdc
url_type2 = 'access' # only when type=http access|debug|error|warning|notice|resources
secret_key = 'xxxxx'
請求地址生成方式可以看一下官網的要求:
&
具體實現代碼如下
params = dict()
params['act'] = 'log'
params['appname'] = appname
params['from'] = from_date
params['to'] = to_date
params['type'] = url_type
if url_type == 'http':
params['type2'] = url_type2
params = collections.OrderedDict(sorted(params.items()))
request = ''
for k,v in params.iteritems():
request += k+'='+v+'&'
sign = request.replace('&','')
sign += secret_key
md5 = hashlib.md5()
md5.update(sign)
sign = md5.hexdigest()
request = api_url + request + 'sign=' + sign
if response['errno'] != 0:
print '[!] '+response['errmsg']
exit()
print '[#] request success'
SAE將每天的日志文件都打包成tar.gz的格式,下載保存下來即可,文件名以日期.tar.gz
命名
log_files = list()
for down_url in response['data']:
file_name = re.compile(r'\d{4}-\d{2}-\d{2}').findall(down_url)[0] + '.tar.gz'
log_files.append(file_name)
data = urllib2.urlopen(down_url).read()
with open(file_name, "wb") as file:
file.write(data)
print '[#] you got %d log files' % len(log_files)
合並文件方式用trafile庫解壓縮每個文件,然後把文件內容附加到access_log下就可以了
# compress these files to access_log
access_log = open('access_log','w');
for log_file in log_files:
tar = tarfile.open(log_file)
log_name = tar.getnames()[0]
tar.extract(log_name)
# save to access_log
data = open(log_name).read()
access_log.write(data)
os.remove(log_name)
print '[#] all file has writen to access_log'