Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python2
- # -*- coding: utf-8 -*-
- import os
- import json
- import subprocess
- """
- Created on Tue Apr 4 15:36:28 2017
- @author: jfk
- """
- ############################################
- # decoupage fichier en plusieurs fichier
- ############################################
- def pathwindowtolinux(name):
- return name.replace('\\','/')
- def pathlinuxtowindow(name):
- return name.replace('\\','/')
- def cmd(cmd):
- obj={}
- p = subprocess.Popen(cmd,
- shell=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT)
- result = p.stdout.readlines()
- obj['code']=p.wait()
- obj['result']=result
- return obj
- def xmllint_exist():
- #test si xmllint est installé.
- re = cmd("xmllint --version")
- return (re['code']==0)
- # remplace dans fichier tous les lit un fichier
- def file_get_contents(filename):
- with file(filename) as f:
- s = f.read()
- return s
- def save(filename, contents):
- fh = open(filename, 'wb')
- fh.write(contents)
- fh.close()
- def createdata():
- data = { 'Name' : '',
- 'CreatedTime' : '',
- 'CreatedBy' : '',
- 'LastModifiedTime' : '',
- 'LastModifiedBy' : '',
- 'ShortName' : '',
- 'Version' : '',
- 'Publisher' : '',
- 'Language' : '',
- 'Source' : '',
- 'CommandLine' : '',
- 'WorkingDirectory' : '',
- 'Reboot' : '',
- 'Dependency' : []
- }
- return data
- def create_descripteur(data):
- tempfileheader = """
- "info": {
- "description": "%s",
- "name": "%s",
- "software": "%s",
- "transferfile": true,
- "version": "%s",
- "CreatedTime" : "%s",
- "CreatedBy" : "%s",
- "LastModifiedTime" : "%s",
- "LastModifiedBy" : "%s",
- "ShortName" : "%s",
- "Publisher" : "%s",
- "Language" : "%s",
- "Dependency" : %s
- }"""%( data['Name'],
- data['Name'],
- data['Name'],
- data['Version'],
- data['CreatedTime'],
- data['CreatedBy'],
- data['LastModifiedTime'],
- data['LastModifiedBy'],
- data['ShortName'],
- data['Publisher'],
- data['Language'],
- data['Dependency'])
- return tempfileheader
- def create_shell(data):
- #tab = data['WorkingDirectory'].split("\\")
- str1=""
- #addition de cette ligne si utilisation 7zip
- ##str1 = '"%%programfiles(x86)%%\\7-Zip\\7z" x -y %s.zip'%data['pacquagename']
- #str1 += os.linesep
- #str1 += "cd \"%s\""%tab[-1]
- str1 += "cd \".\\%s\""%data['WorkingDirectory']
- str1 += os.linesep
- str1 += "%s"%data['CommandLine']
- return str1
- def first_step_descripteur(data, clearsrc ):
- if clearsrc :
- clearing = "true"
- else:
- clearing = "false"
- if data['Reboot'] :
- tempfile = """
- "win": {
- "sequence": [
- {
- "step": 0,
- "action": "action_pwd_package"
- },
- {
- "step" : 1,
- "action" : "action_unzip_file",
- "filename" : "@@@UUID_PACKAGE@@@.zip",
- "pathdirectorytounzip" : "@@@PACKAGE_DIRECTORY_ABS_MACHINE@@@",
- "@resultcommand" : ""
- },
- {
- "step": 2,
- "@resultcommand": "",
- "action": "actionprocessscript",
- "codereturn": "",
- "command": "xmppdeploy.bat",
- "error": 5,
- "success": 3,
- "timeout": 900
- },
- {
- "step": 3,
- "action": "actionrestart"
- },
- {
- "action": "actionsuccescompletedend",
- "step": 4,
- "clear" : %s
- },
- {
- "action": "actionerrorcompletedend",
- "step": 5,
- "clear" : %s
- }
- ]
- }"""%(clearing, clearing)
- else:
- tempfile = """
- "win": {
- "sequence": [
- {
- "action": "action_pwd_package",
- "step": 0
- },
- {
- "step" : 1,
- "action" : "action_unzip_file",
- "filename" : "@@@UUID_PACKAGE@@@.zip",
- "pathdirectorytounzip" : "@@@PACKAGE_DIRECTORY_ABS_MACHINE@@@",
- "@resultcommand" : ""
- },
- {
- "step": 2,
- "@resultcommand": "",
- "action": "actionprocessscript",
- "codereturn": "",
- "command": "xmppdeploy.bat",
- "success": 3,
- "error": 4,
- "timeout": 900
- },
- {
- "action": "actionsuccescompletedend",
- "step": 3,
- "clear" : %s
- },
- {
- "action": "actionerrorcompletedend",
- "step": 4,
- "clear" : %s
- }
- ]
- }"""%(clearing, clearing)
- return tempfile
- def create_conf_json(id, name, description):
- tmpconf ="""{"commands":
- {
- "postCommandSuccess":
- {"command": "", "name": ""},
- "installInit":
- {"command": "", "name": ""},
- "postCommandFailure":
- {"command": "", "name": ""},
- "command": {"command": "xmppdeploy.bat", "name": ""},
- "preCommand": {"command": "", "name": ""}
- },
- "description": "%s",
- "targetos": "linux",
- "entity_id": "0",
- "sub_packages": [],
- "reboot": 0,
- "version": "0.1",
- "inventory": {
- "associateinventory": "0",
- "licenses": "",
- "queries": {"Qversion": "", "Qvendor": "", "boolcnd": "", "Qsoftware": ""}
- },
- "id": "%s",
- "name": "%s"
- }"""%(description, id, name)
- return tmpconf
- if __name__ == '__main__':
- # pour debug ne genere pas les zip (long à générer.)
- ziping = False
- clearsrc = False
- curentpath = os.getcwd()
- xmllinttrue = xmllint_exist()
- filename = os.path.join('/','home','jfk','Documents','testxml.xml')
- #duplique xml
- filenamenew = os.path.join('/','home','jfk','Documents','Applicationsnew.xml')
- directoryfile = os.path.join('/','home','jfk','Documents','xmldata')
- descripteurname ="xmppdeploy.json"
- basefilewindos = r'/home/jfk/Documents/app/Applications/'
- #basefilewindos = r'/home/jfk/Documents/app/'
- #creation directory des descripteurs.
- catalogue = os.path.join(directoryfile, 'catalog.txt')
- try:
- os.makedirs(os.path.join(directoryfile), mode=0777)
- except Exception:
- pass
- fc = open(catalogue, 'w')
- fc.write("LIST GENERATED PACKAGES\n\n")
- #recupere contenue fichier
- strfile = file_get_contents(filename)
- # decompose fichier xml par tags
- newstr = strfile.replace("><", ">" + os.linesep + "<")
- strfile = None
- # sauve le fichier à traité dans le fichier filenamenew.
- save(filenamenew, newstr )
- newstr = None
- #recupere des lignes du fichier dans un tableau
- f = open(filenamenew, 'r')
- lignes = f.readlines()
- f.close()
- #analyse chaque ligne de tableau
- fh = None
- for ligne in lignes:
- #print ligne
- ligne = ligne.strip()
- #ignore ligne vide ou tag xml terminal or tag applications.
- if ligne == "" or\
- ligne.endswith("/>") or\
- ligne.startswith("</applications") or\
- ligne.startswith("<applications"):
- continue
- if ligne.startswith("<application guid=\"{"):
- # debut de package dans le xml
- # creation d'une structure contenant les information de xml pour une application
- dep=[]
- data = createdata()
- keydata = data.keys()
- #on recupere uuid comme namefile
- namefile = ligne[20:56]
- try:
- #on cre le directory du package.
- #print os.path.join(directoryfile, namefile)
- os.makedirs(os.path.join(directoryfile, namefile), mode=0777)
- except Exception:
- pass
- if fh is not None:
- #print "close file"
- #fh.write("</application>")
- fh.close()
- if xmllinttrue:
- #mise en forme xml
- namexml = "xmllint --format %s > %s; rm %s"%(
- os.path.join(directoryfile, namefile, 'data.xml'),
- os.path.join(directoryfile, namefile, 'data1.xml'),
- os.path.join(directoryfile, namefile, 'data.xml')
- )
- #print namexml
- cmd(namexml)
- #try:
- # os.remove(os.path.join(directoryfile, namefile, 'data.xml'))
- #except Exception as e:
- # print str(e)
- # pass
- fh = None
- #on reseigne la structure de données savec uuid du package
- data['pacquagename'] = namefile
- if fh is None:
- #print "open file"
- #on cree un fichier xml de data dans un répertoire
- fh = open(os.path.join(directoryfile, namefile, 'data.xml'), 'wb')
- fh.write(ligne)
- else:
- #on est dans un descripteur xml d application
- if ligne.endswith("</application>"):
- fh.write("</application>")
- #tag application terminal on écrit le descripteur dans 'data.json'
- #write file
- descriptor= """{
- %s,
- %s
- }"""% (create_descripteur(data), first_step_descripteur(data, clearsrc))
- descriptor = descriptor.replace(os.linesep,"")
- descriptor = descriptor.replace(" "," ")
- descriptor = descriptor.replace(" "," ")
- descriptor = descriptor.replace(" "," ")
- descriptor = descriptor.replace(" "," ")
- descriptor = descriptor.replace(" "," ")
- descriptor = descriptor.replace(" "," ")
- fc.write("Name [%s]\npackages [%s]\nversion [%s]\n\n"%(data['Name'], namefile , data['Version']))
- d = json.loads(descriptor)
- descriptorstr = json.dumps(d, indent=4)
- with open(os.path.join(directoryfile, namefile, 'data.json'), 'w') as outfile:
- json.dump(data, outfile)
- #write descriptor
- fd = open(os.path.join(directoryfile, namefile, descripteurname), 'wb')
- fd.write(descriptorstr)
- fd.close()
- #create conf.json ancien decriptor packages.
- descconf = create_conf_json( data['pacquagename'], data['Name'], "generation automatic "+ data['Name'])
- fd = open(os.path.join(directoryfile, namefile, "conf.json"), 'wb')
- fd.write(descconf)
- fd.close()
- ##ziper les repertoire dans le package
- #on supprime .\Applications\ du path
- if data['WorkingDirectory'] == "":
- print "\n******************************WARNING************************************************"
- print "WorkingDirectory missing for package : [%s] name : [%s]"%(namefile , data['Name'] )
- print "Error impossible create zip file for package\n"
- if xmllinttrue:
- print file_get_contents(os.path.join(directoryfile, namefile, 'data1.xml'))
- else:
- print file_get_contents(os.path.join(directoryfile, namefile, 'data1.xml'))
- print"***************************************************************************************\n"
- fc.write("\n\t***Warning Name [%s]\n\tpackages [%s]\n\tversion [%s]\n"%(data['Name'], namefile , data['Version']))
- fc.write("\timpossible create zip file for package : WorkingDirectory missing in xml\n\n")
- elif data['WorkingDirectory'].startswith(".\Applications"):
- print "Generated Package %s name %s version %s "%(data['Name'], namefile , data['Version'])
- data['WorkingDirectory'] = data['WorkingDirectory'][15:]
- os.chdir(basefilewindos)
- #print os.getcwd()
- command = 'zip -r %s.zip "%s"'%(os.path.join(directoryfile, namefile, data['pacquagename']),\
- pathwindowtolinux(data['WorkingDirectory']))
- # print "***********************"
- #print command
- if ziping:
- re = cmd(command)
- # print re['result']
- # print "***********************"
- else:
- print "\n******************************WARNING************************************************"
- print "WorkingDirectory False for package : [%s] name : [%s]"%(namefile , data['Name'] )
- print "Error : impossible create zip file for package"
- print "WorkingDirectory in xml is : %s\n"% data['WorkingDirectory']
- if xmllinttrue:
- print file_get_contents(os.path.join(directoryfile, namefile, 'data1.xml'))
- else:
- print file_get_contents(os.path.join(directoryfile, namefile, 'data1.xml'))
- print"***************************************************************************************\n"
- fc.write("\n\t***Warning Name [%s]\n\tpackages [%s]\n\tversion [%s]\n"%(data['Name'], namefile , data['Version']))
- fc.write("\timpossible create zip file for package : WorkingDirectory is not exist [%s]\n\n"%data['WorkingDirectory'])
- fd = open(os.path.join(directoryfile, namefile, "xmppdeploy.bat"), 'wb')
- fd.write(create_shell(data))
- fd.close()
- continue
- #recupere key xml
- # rempli structure avec valeur xml
- if ligne.startswith("<"):
- l1 = ligne.split(">")
- clef = l1[0][1:]
- #print "clef", clef
- #print ligne
- if not clef in data:
- print "warning pas cette clef \"%s\""%clef
- else:
- ligne1 = ligne.replace("<"+clef+">","" )
- ligne1 = ligne1.replace("</"+clef+">","")
- if(clef != "WorkingDirectory" ):
- #supprimer caractere interdit pour json
- ligne1 = ligne1.replace('\\',' ')
- if clef == "Dependency":
- line2 = ligne1.replace("{","")
- line2 = line2.replace("}","")
- dep.append(line2)
- deps=str(dep)
- data[clef] = deps.replace("'", '"')
- else:
- data[clef] = ligne1
- if fh is not None:
- fh.write(ligne)
- if fh is not None:
- fh.write(ligne)
- fh.close()
- #close catalogue
- fc.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement