程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> Python >> Python腳本--下載合並SAE日志

Python腳本--下載合並SAE日志

編輯:Python

Python腳本–下載合並SAE日志

由於一些原因,需要SAE上站點的日志文件,從SAE上只能按天下載,下載下來手動處理比較蛋疼,尤其是數量很大的時候。還好SAE提供了API可以批量獲得日志文件下載地址,剛剛寫了python腳本自動下載和合並這些文件

調用API獲得下載地址

文檔位置在這裡

設置自己的應用和下載參數

請求中需要設置的變量如下

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'

生成請求地址

請求地址生成方式可以看一下官網的要求:

  1. 將參數排序
  2. 生成請求字符串,去掉&
  3. 附加access_key
  4. 請求字符串求md5,形成sign
  5. 把sign增加到請求字符串中

具體實現代碼如下

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'
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved