python自動化常用模塊

python自動化常用模塊

來自專欄 運維

#!/usr/bin/env python# -*- coding: utf-8 -*-import subprocessimport sys, osimport commandsimport shutilimport reimport hashlib import urllibimport oss2import argparsefrom urlparse import urlparseimport timeimport randomimport jsonfrom xml.etree.ElementTree import ElementTree,Elementfrom string import replaceimport requests#--------1--------標記# 列印各種顏色的logclass Log: @staticmethod def e(msg): print(Log.red + [x]: + msg + Log.end) @staticmethod def w(msg): print(Log.yellow + [!]: + msg + Log.end) @staticmethod def i(msg): print(Log.green + [+]: + msg + Log.end) @staticmethod def t(msg): print(Log.blue + [-]: + msg + Log.end) red = 33[1;31m green = 33[1;32m yellow = 33[1;33m blue = 33[1;34m end = 33[00m# 簡單標記markdef mark(marked_words): print_words = "|=|-----"+marked_words+"
" print print_words#--------2--------上傳# 單個文件上傳到ossdef upload_file_oss(): auth = oss2.Auth(填寫自己的AccessKey, 填寫自己的AccessKeySecret) bucket = oss2.Bucket(auth, 填寫域名, 填寫bucket) apkname="test.apk" apk_save_path="./test" bucket.put_object_from_file(test/+apkname, apk_save_path+/+apkname)# 遍歷目錄def List_Folder_Contents(rootDir,f): for lists in os.listdir(rootDir): path = os.path.join(rootDir, lists) if(os.path.isfile(path)): print path f.append(path) if os.path.isdir(path): List_Folder_Contents(path,f) return f# 上傳目錄到ossdef upload_dir_oss(): auth = oss2.Auth(填寫自己的AccessKey, 填寫自己的AccessKeySecret) bucket = oss2.Bucket(auth, 填寫域名, 填寫bucket) ### 遍歷目錄 Log.i("list dirs files") output_path="./test" f = [] f=List_Folder_Contents(output_path,f)#調用List_Folder_Contents函數 print f ### 上傳OSS Log.w("upload dir to OSS") for i, val in enumerate(f): print ("key:%s value:%s" % (i + 1, val)) list_name=val.split("/")[-2]+"/"+val.split("/")[-1] Log.i("list_name:"+list_name) result = bucket.put_object_from_file(/test/+list_name,val) print(http status: {0}.format(result.status)) if(result.status == 200): Log.i("upload:"+val+" to OSS success")#--------3--------json# touch filedef Touch(file_name,file_path): os.chdir(file_path) if file_name in os.listdir(.): print("file exist!") else: print("creating %s" %file_name) fid = open(file_name,w) fid.close()# create json 文件def create_json(changeLog,marketCode,md5,url,versionCode,versionName,json_name): json_save_path = "./test" if not os.path.exists(json_save_path): os.makedirs(json_save_path) Log.t(Create json_save_path:+json_save_path) Touch(json_name,json_save_path) # write json to file Log.i("start to write json info to file") public_path="./" json_path=public_path+/+json_name file =json_path fb = open(file,w) data={"changeLog":changeLog,"key1":value1,"key2":value2,"key3":value3,"key4":key4,"key5":key5} dataDict=json.dumps(data, ensure_ascii=False, sort_keys=True, indent=4, separators=(,, : )).replace("\n","n") print dataDict fb.write(dataDict) fb.close() return json_path#--------4--------md5# 計算md5_FILE_SLIM=100*1024*1024def File_md5(filepath): calltimes = 0 hmd5 = hashlib.md5() fp = open(filepath, "rb") f_size = os.stat(filepath).st_size if f_size > _FILE_SLIM: while (f_size > _FILE_SLIM): hmd5.update(fp.read(_FILE_SLIM)) f_size /= _FILE_SLIM calltimes += 1 if (f_size > 0) and (f_size <= _FILE_SLIM): hmd5.update(fp.read()) else: hmd5.update(fp.read()) return hmd5.hexdigest()# 驗證md5值 (與download連用)def verify_md5(md5,url,save_path,filename): Log.i("verify md5 vaule") download(url,save_path,filename) download_md5 = File_md5(save_path+/+filename) Log.e("md5:"+md5+" download_md5:"+download_md5) if download_md5 == md5: Log.i("md5 right") else: Log.i("md5 wrong") quit()#--------5--------雜七雜八# 下載文件def download(url_str,save_path,filename): full_path = save_path + / + filename Log.i("full_path:"+full_path) try: urllib.urlretrieve(url_str,full_path) print "download success" return full_path except: print "download failed" return False# 讀取changeLog.txtdef readChanegLog(filepath): info = open(filepath).read() info = info.decode(utf-8) new_info = info.replace(
,\n) return new_info# 獲取隨機值def getRandomNum(num): pool=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 i = 0 randomNum= while i < num: i+=1 tmp = random.choice(pool) randomNum = randomNum+tmp return randomNum# 從URL中獲取文件名def get_filename(url_str): url = urlparse(url_str) i = len(url.path) - 1 while i > 0: if url.path[i] == /: break i = i - 1 filename=url.path[i+1:len(url.path)] if not filename.strip(): return False return filename# 上傳介面def upload_api(): Log.i("post API start") default_url = "http://xx.xxxx.cn/xxxxx/xxxxxx/xxxxx/xxxxx.php" data={"key1":value1,"key2":value2} dataDict=json.dumps(data, ensure_ascii=False, sort_keys=True, indent=4, separators=(,, : )) r = requests.post(default_url, data) print dataDict Log.i("post API finish")# 接收參數def parserParameter(): parser = argparse.ArgumentParser(description=This is update script!) required = parser.add_argument_group(required arguments) parser.add_argument(--name1, required=True, help=apk name(formate:{k1}-{k2}-{k3}-v{k4}.apk)) parser.add_argument(--name2, required=True, help=XXXX) args = parser.parse_args() return argsif __name__ == __main__: ### 解析參數 args=parserParameter() name1=args.name1 name2=args.name2

推薦閱讀:

TAG:Python | Python入門 | 編程語言 |