Advertisement
Guest User

Untitled

a guest
Apr 25th, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.55 KB | None | 0 0
  1. #!/usr/bin/env python2
  2. # -*- coding: utf-8 -*-
  3. import os
  4. import json
  5. import subprocess
  6.  
  7. """
  8. Created on Tue Apr 4 15:36:28 2017
  9.  
  10. @author: jfk
  11. """
  12. ############################################
  13. # decoupage fichier en plusieurs fichier
  14. ############################################
  15. def pathwindowtolinux(name):
  16. return name.replace('\\','/')
  17.  
  18. def pathlinuxtowindow(name):
  19. return name.replace('\\','/')
  20.  
  21.  
  22. def cmd(cmd):
  23. obj={}
  24. p = subprocess.Popen(cmd,
  25. shell=True,
  26. stdout=subprocess.PIPE,
  27. stderr=subprocess.STDOUT)
  28. result = p.stdout.readlines()
  29. obj['code']=p.wait()
  30. obj['result']=result
  31. return obj
  32.  
  33. def xmllint_exist():
  34. #test si xmllint est installé.
  35. re = cmd("xmllint --version")
  36. return (re['code']==0)
  37.  
  38. # remplace dans fichier tous les lit un fichier
  39. def file_get_contents(filename):
  40. with file(filename) as f:
  41. s = f.read()
  42. return s
  43.  
  44. def save(filename, contents):
  45. fh = open(filename, 'wb')
  46. fh.write(contents)
  47. fh.close()
  48.  
  49. def createdata():
  50. data = { 'Name' : '',
  51. 'CreatedTime' : '',
  52. 'CreatedBy' : '',
  53. 'LastModifiedTime' : '',
  54. 'LastModifiedBy' : '',
  55. 'ShortName' : '',
  56. 'Version' : '',
  57. 'Publisher' : '',
  58. 'Language' : '',
  59. 'Source' : '',
  60. 'CommandLine' : '',
  61. 'WorkingDirectory' : '',
  62. 'Reboot' : '',
  63. 'Dependency' : []
  64. }
  65. return data
  66.  
  67. def create_descripteur(data):
  68. tempfileheader = """
  69. "info": {
  70. "description": "%s",
  71. "name": "%s",
  72. "software": "%s",
  73. "transferfile": true,
  74. "version": "%s",
  75. "CreatedTime" : "%s",
  76. "CreatedBy" : "%s",
  77. "LastModifiedTime" : "%s",
  78. "LastModifiedBy" : "%s",
  79. "ShortName" : "%s",
  80. "Publisher" : "%s",
  81. "Language" : "%s",
  82. "Dependency" : %s
  83. }"""%( data['Name'],
  84. data['Name'],
  85. data['Name'],
  86. data['Version'],
  87. data['CreatedTime'],
  88. data['CreatedBy'],
  89. data['LastModifiedTime'],
  90. data['LastModifiedBy'],
  91. data['ShortName'],
  92. data['Publisher'],
  93. data['Language'],
  94. data['Dependency'])
  95. return tempfileheader
  96.  
  97. def create_shell(data):
  98. #tab = data['WorkingDirectory'].split("\\")
  99. str1=""
  100. #addition de cette ligne si utilisation 7zip
  101. ##str1 = '"%%programfiles(x86)%%\\7-Zip\\7z" x -y %s.zip'%data['pacquagename']
  102. #str1 += os.linesep
  103. #str1 += "cd \"%s\""%tab[-1]
  104. str1 += "cd \".\\%s\""%data['WorkingDirectory']
  105. str1 += os.linesep
  106. str1 += "%s"%data['CommandLine']
  107. return str1
  108.  
  109. def first_step_descripteur(data, clearsrc ):
  110. if clearsrc :
  111. clearing = "true"
  112. else:
  113. clearing = "false"
  114.  
  115. if data['Reboot'] :
  116. tempfile = """
  117. "win": {
  118. "sequence": [
  119. {
  120. "step": 0,
  121. "action": "action_pwd_package"
  122. },
  123. {
  124. "step" : 1,
  125. "action" : "action_unzip_file",
  126. "filename" : "@@@UUID_PACKAGE@@@.zip",
  127. "pathdirectorytounzip" : "@@@PACKAGE_DIRECTORY_ABS_MACHINE@@@",
  128. "@resultcommand" : ""
  129. },
  130. {
  131. "step": 2,
  132. "@resultcommand": "",
  133. "action": "actionprocessscript",
  134. "codereturn": "",
  135. "command": "xmppdeploy.bat",
  136. "error": 5,
  137. "success": 3,
  138. "timeout": 900
  139. },
  140. {
  141. "step": 3,
  142. "action": "actionrestart"
  143. },
  144. {
  145. "action": "actionsuccescompletedend",
  146. "step": 4,
  147. "clear" : %s
  148. },
  149. {
  150. "action": "actionerrorcompletedend",
  151. "step": 5,
  152. "clear" : %s
  153. }
  154. ]
  155. }"""%(clearing, clearing)
  156. else:
  157. tempfile = """
  158. "win": {
  159. "sequence": [
  160. {
  161. "action": "action_pwd_package",
  162. "step": 0
  163. },
  164. {
  165. "step" : 1,
  166. "action" : "action_unzip_file",
  167. "filename" : "@@@UUID_PACKAGE@@@.zip",
  168. "pathdirectorytounzip" : "@@@PACKAGE_DIRECTORY_ABS_MACHINE@@@",
  169. "@resultcommand" : ""
  170. },
  171. {
  172. "step": 2,
  173. "@resultcommand": "",
  174. "action": "actionprocessscript",
  175. "codereturn": "",
  176. "command": "xmppdeploy.bat",
  177. "success": 3,
  178. "error": 4,
  179. "timeout": 900
  180. },
  181. {
  182. "action": "actionsuccescompletedend",
  183. "step": 3,
  184. "clear" : %s
  185. },
  186. {
  187. "action": "actionerrorcompletedend",
  188. "step": 4,
  189. "clear" : %s
  190. }
  191. ]
  192. }"""%(clearing, clearing)
  193. return tempfile
  194.  
  195. def create_conf_json(id, name, description):
  196. tmpconf ="""{"commands":
  197. {
  198. "postCommandSuccess":
  199. {"command": "", "name": ""},
  200. "installInit":
  201. {"command": "", "name": ""},
  202. "postCommandFailure":
  203. {"command": "", "name": ""},
  204. "command": {"command": "xmppdeploy.bat", "name": ""},
  205. "preCommand": {"command": "", "name": ""}
  206. },
  207. "description": "%s",
  208. "targetos": "linux",
  209. "entity_id": "0",
  210. "sub_packages": [],
  211. "reboot": 0,
  212. "version": "0.1",
  213. "inventory": {
  214. "associateinventory": "0",
  215. "licenses": "",
  216. "queries": {"Qversion": "", "Qvendor": "", "boolcnd": "", "Qsoftware": ""}
  217. },
  218. "id": "%s",
  219. "name": "%s"
  220. }"""%(description, id, name)
  221.  
  222. return tmpconf
  223.  
  224.  
  225. if __name__ == '__main__':
  226. # pour debug ne genere pas les zip (long à générer.)
  227. ziping = False
  228. clearsrc = False
  229. curentpath = os.getcwd()
  230. xmllinttrue = xmllint_exist()
  231.  
  232. filename = os.path.join('/','home','jfk','Documents','testxml.xml')
  233. #duplique xml
  234. filenamenew = os.path.join('/','home','jfk','Documents','Applicationsnew.xml')
  235. directoryfile = os.path.join('/','home','jfk','Documents','xmldata')
  236. descripteurname ="xmppdeploy.json"
  237.  
  238. basefilewindos = r'/home/jfk/Documents/app/Applications/'
  239. #basefilewindos = r'/home/jfk/Documents/app/'
  240. #creation directory des descripteurs.
  241. catalogue = os.path.join(directoryfile, 'catalog.txt')
  242. try:
  243. os.makedirs(os.path.join(directoryfile), mode=0777)
  244. except Exception:
  245. pass
  246.  
  247. fc = open(catalogue, 'w')
  248. fc.write("LIST GENERATED PACKAGES\n\n")
  249.  
  250. #recupere contenue fichier
  251. strfile = file_get_contents(filename)
  252. # decompose fichier xml par tags
  253. newstr = strfile.replace("><", ">" + os.linesep + "<")
  254. strfile = None
  255.  
  256. # sauve le fichier à traité dans le fichier filenamenew.
  257. save(filenamenew, newstr )
  258. newstr = None
  259. #recupere des lignes du fichier dans un tableau
  260. f = open(filenamenew, 'r')
  261. lignes = f.readlines()
  262. f.close()
  263.  
  264. #analyse chaque ligne de tableau
  265. fh = None
  266. for ligne in lignes:
  267. #print ligne
  268. ligne = ligne.strip()
  269.  
  270. #ignore ligne vide ou tag xml terminal or tag applications.
  271. if ligne == "" or\
  272. ligne.endswith("/>") or\
  273. ligne.startswith("</applications") or\
  274. ligne.startswith("<applications"):
  275. continue
  276.  
  277.  
  278. if ligne.startswith("<application guid=\"{"):
  279. # debut de package dans le xml
  280. # creation d'une structure contenant les information de xml pour une application
  281. dep=[]
  282. data = createdata()
  283. keydata = data.keys()
  284. #on recupere uuid comme namefile
  285. namefile = ligne[20:56]
  286. try:
  287. #on cre le directory du package.
  288. #print os.path.join(directoryfile, namefile)
  289. os.makedirs(os.path.join(directoryfile, namefile), mode=0777)
  290. except Exception:
  291. pass
  292.  
  293. if fh is not None:
  294. #print "close file"
  295. #fh.write("</application>")
  296. fh.close()
  297. if xmllinttrue:
  298. #mise en forme xml
  299. namexml = "xmllint --format %s > %s; rm %s"%(
  300. os.path.join(directoryfile, namefile, 'data.xml'),
  301. os.path.join(directoryfile, namefile, 'data1.xml'),
  302. os.path.join(directoryfile, namefile, 'data.xml')
  303. )
  304. #print namexml
  305.  
  306. cmd(namexml)
  307. #try:
  308. # os.remove(os.path.join(directoryfile, namefile, 'data.xml'))
  309. #except Exception as e:
  310. # print str(e)
  311. # pass
  312. fh = None
  313.  
  314. #on reseigne la structure de données savec uuid du package
  315. data['pacquagename'] = namefile
  316. if fh is None:
  317. #print "open file"
  318. #on cree un fichier xml de data dans un répertoire
  319. fh = open(os.path.join(directoryfile, namefile, 'data.xml'), 'wb')
  320. fh.write(ligne)
  321. else:
  322. #on est dans un descripteur xml d application
  323. if ligne.endswith("</application>"):
  324. fh.write("</application>")
  325. #tag application terminal on écrit le descripteur dans 'data.json'
  326. #write file
  327. descriptor= """{
  328. %s,
  329. %s
  330. }"""% (create_descripteur(data), first_step_descripteur(data, clearsrc))
  331. descriptor = descriptor.replace(os.linesep,"")
  332. descriptor = descriptor.replace(" "," ")
  333. descriptor = descriptor.replace(" "," ")
  334. descriptor = descriptor.replace(" "," ")
  335. descriptor = descriptor.replace(" "," ")
  336. descriptor = descriptor.replace(" "," ")
  337. descriptor = descriptor.replace(" "," ")
  338. fc.write("Name [%s]\npackages [%s]\nversion [%s]\n\n"%(data['Name'], namefile , data['Version']))
  339. d = json.loads(descriptor)
  340. descriptorstr = json.dumps(d, indent=4)
  341. with open(os.path.join(directoryfile, namefile, 'data.json'), 'w') as outfile:
  342. json.dump(data, outfile)
  343. #write descriptor
  344. fd = open(os.path.join(directoryfile, namefile, descripteurname), 'wb')
  345. fd.write(descriptorstr)
  346. fd.close()
  347. #create conf.json ancien decriptor packages.
  348.  
  349.  
  350. descconf = create_conf_json( data['pacquagename'], data['Name'], "generation automatic "+ data['Name'])
  351. fd = open(os.path.join(directoryfile, namefile, "conf.json"), 'wb')
  352. fd.write(descconf)
  353. fd.close()
  354. ##ziper les repertoire dans le package
  355. #on supprime .\Applications\ du path
  356. if data['WorkingDirectory'] == "":
  357. print "\n******************************WARNING************************************************"
  358. print "WorkingDirectory missing for package : [%s] name : [%s]"%(namefile , data['Name'] )
  359. print "Error impossible create zip file for package\n"
  360. if xmllinttrue:
  361. print file_get_contents(os.path.join(directoryfile, namefile, 'data1.xml'))
  362. else:
  363. print file_get_contents(os.path.join(directoryfile, namefile, 'data1.xml'))
  364. print"***************************************************************************************\n"
  365. fc.write("\n\t***Warning Name [%s]\n\tpackages [%s]\n\tversion [%s]\n"%(data['Name'], namefile , data['Version']))
  366. fc.write("\timpossible create zip file for package : WorkingDirectory missing in xml\n\n")
  367. elif data['WorkingDirectory'].startswith(".\Applications"):
  368.  
  369. print "Generated Package %s name %s version %s "%(data['Name'], namefile , data['Version'])
  370. data['WorkingDirectory'] = data['WorkingDirectory'][15:]
  371. os.chdir(basefilewindos)
  372. #print os.getcwd()
  373. command = 'zip -r %s.zip "%s"'%(os.path.join(directoryfile, namefile, data['pacquagename']),\
  374. pathwindowtolinux(data['WorkingDirectory']))
  375. # print "***********************"
  376. #print command
  377. if ziping:
  378. re = cmd(command)
  379. # print re['result']
  380. # print "***********************"
  381. else:
  382. print "\n******************************WARNING************************************************"
  383. print "WorkingDirectory False for package : [%s] name : [%s]"%(namefile , data['Name'] )
  384. print "Error : impossible create zip file for package"
  385. print "WorkingDirectory in xml is : %s\n"% data['WorkingDirectory']
  386. if xmllinttrue:
  387. print file_get_contents(os.path.join(directoryfile, namefile, 'data1.xml'))
  388. else:
  389. print file_get_contents(os.path.join(directoryfile, namefile, 'data1.xml'))
  390. print"***************************************************************************************\n"
  391. fc.write("\n\t***Warning Name [%s]\n\tpackages [%s]\n\tversion [%s]\n"%(data['Name'], namefile , data['Version']))
  392. fc.write("\timpossible create zip file for package : WorkingDirectory is not exist [%s]\n\n"%data['WorkingDirectory'])
  393.  
  394. fd = open(os.path.join(directoryfile, namefile, "xmppdeploy.bat"), 'wb')
  395. fd.write(create_shell(data))
  396. fd.close()
  397. continue
  398.  
  399. #recupere key xml
  400. # rempli structure avec valeur xml
  401. if ligne.startswith("<"):
  402. l1 = ligne.split(">")
  403. clef = l1[0][1:]
  404. #print "clef", clef
  405. #print ligne
  406. if not clef in data:
  407. print "warning pas cette clef \"%s\""%clef
  408. else:
  409. ligne1 = ligne.replace("<"+clef+">","" )
  410. ligne1 = ligne1.replace("</"+clef+">","")
  411. if(clef != "WorkingDirectory" ):
  412. #supprimer caractere interdit pour json
  413. ligne1 = ligne1.replace('\\',' ')
  414.  
  415. if clef == "Dependency":
  416. line2 = ligne1.replace("{","")
  417. line2 = line2.replace("}","")
  418. dep.append(line2)
  419. deps=str(dep)
  420. data[clef] = deps.replace("'", '"')
  421. else:
  422. data[clef] = ligne1
  423. if fh is not None:
  424. fh.write(ligne)
  425.  
  426.  
  427. if fh is not None:
  428.  
  429. fh.write(ligne)
  430. fh.close()
  431. #close catalogue
  432. fc.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement