Guest User

update-java.py

a guest
Jul 31st, 2016
367
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.67 KB | None | 0 0
  1. #!/usr/bin/env python
  2. from string import Template
  3. from datetime import datetime, timedelta
  4. import subprocess
  5. import os
  6. import glob
  7. import shutil
  8. import time
  9.  
  10. def unix_time(dt):
  11.     epoch = datetime.utcfromtimestamp(0)
  12.     return int((dt - epoch).total_seconds())
  13.  
  14. def make_cookies(cookies):
  15.     cookieTemplate = Template('.${domain}\t${allmachines}\t${path}\t${secure}\t${expiration}\t${name}\t${value}\n')
  16.     tomorrow = unix_time(datetime.now() + timedelta(days=1))
  17.     d = dict(
  18.         domain = 'oracle.com',
  19.         allmachines = 'TRUE',
  20.         path = '/',
  21.         secure = 'FALSE',
  22.         expiration = tomorrow,
  23.         name = 'oraclelicense',
  24.         value = 'accept-securebackup-cookie'
  25.     )
  26.     cookieString = cookieTemplate.safe_substitute(d)
  27.     with open(cookies,'w') as f:
  28.         f.write(cookieString)
  29.  
  30. def find_latest_update(version):
  31.     versionUrl = Template("http://java.com/en/download/installed${version}.jsp")
  32.     url = versionUrl.safe_substitute(version=version)
  33.     output = subprocess.check_output(["wget", "-qO-", url])
  34.     tagLine = Template("latest${version}Version").safe_substitute(version=version)
  35.     for line in output.split('\n'):
  36.         if tagLine in line:
  37.             #print line
  38.             (_, versionString, _) = line.split("'")
  39.             # print versionString # 1.8.0_101
  40.             (_, update) = versionString.split("_")
  41.             # print update # 101
  42.             return int(update)
  43.  
  44. def download_java(kinds, version, update, cookies):
  45.     site = "http://download.oracle.com/otn-pub/java/jdk"
  46.     b = 13 # not sure how often this changes
  47.     archList = ["windows-x64", "windows-i586"]
  48.     urlTemplate = Template("${site}/${version}u${update}-b${b}/${package}-${version}u${update}-${arch}.exe")
  49.     for arch in archList:
  50.         for package in kinds:
  51.             d = dict(
  52.                 site = site,
  53.                 package = package,
  54.                 version = version,
  55.                 update = update,
  56.                 b = b,
  57.                 arch = arch
  58.             )
  59.             url = urlTemplate.safe_substitute(d)
  60.             print "Downloading %s" % (url)
  61.             cookieFlag = "--load-cookies=%s" % (cookies)
  62.             subprocess.call(["wget", "-q", cookieFlag, url],
  63.                             cwd = os.getcwd())
  64.  
  65. def copy_java_contents(kinds, version, update, msiDestination):
  66.     # For each executable with correct version and update
  67.     patternTemplate=Template("${kind}-${version}u${update}-windows-*.exe")
  68.     for kind in kinds:
  69.         d = dict(
  70.             kind = kind,
  71.             version = version,
  72.             update = update
  73.         )
  74.         pattern = patternTemplate.safe_substitute(d)
  75.         olddir = os.getcwd()
  76.         for file in glob.glob(pattern):
  77.             print file
  78.             # - Make a directory in wpkg/software
  79.             (_, _, _, archexe) = file.split("-")
  80.             if archexe=="i586.exe":
  81.                 arch = "x86"
  82.             elif archexe=="x64.exe":
  83.                 arch = "x64"
  84.             path = msiDestination + (r'\%s\%d\%d-%s '[:-1] % (kind,
  85.                                                               version,
  86.                                                               update,
  87.                                                               arch))
  88.             print "Will makedirs(%s) if needed" % (path)
  89.             if not os.path.isdir(path):
  90.                 os.makedirs(path, mode = 0755)
  91.             # - Run the executable to extract contents to temp
  92.             print "Starting %s" % (file)
  93.             proc = subprocess.Popen([file], shell=False)
  94.             print "Started %s as %s" % (file, proc)
  95.             # - Copy contents to wpkg directory
  96.             extract_parent = os.path.join(os.environ['USERPROFILE'], 'Appdata',
  97.                                           'LocalLow', 'Oracle', 'Java')
  98.             print "Chccking for extract parent directory %s..." % (extract_parent),
  99.             while not os.path.isdir(extract_parent):
  100.                 time.sleep(1)
  101.             os.chdir(extract_parent)
  102.             print "done."
  103.             if arch=="x64":
  104.                 tempFolder = "%s1.%d.0_%d_%s" % (kind, version, update, arch)
  105.             else:
  106.                 tempFolder = "%s1.%d.0_%d" % (kind, version, update)
  107.             print "Checking for extract directory...",
  108.             while not os.path.isdir(tempFolder):
  109.                 time.sleep(1)
  110.             os.chdir(tempFolder)
  111.             print "done."
  112.             print "Sleeping for 10 seconds...",
  113.             time.sleep(10)
  114.             print "done."
  115.             # - Kill the executable
  116.             subprocess.call(['taskkill', '/F', '/T', '/PID', str(proc.pid)])
  117.             print "Copying files...",
  118.             for f in glob.glob("*.msi"):
  119.                 shutil.copy(f,path)
  120.             for f in glob.glob("*.cab"):
  121.                 shutil.copy(f,path)
  122.             print "done."
  123.             os.chdir('..')
  124.             # - Remove contents from temp
  125.             shutil.rmtree(tempFolder)
  126.             os.chdir(olddir)
  127.  
  128. def update_java_packages(kinds, version, update, wpkgRoot, branches):
  129.     for kind in kinds:
  130.         for branch in branches:
  131.             sourceXML = "%s-%d.xml" % (kind, version)
  132.             with open(sourceXML) as templateXML:
  133.                 lines=templateXML.readlines()
  134.             template = Template( ''.join(lines) )
  135.             d=dict(update=update)
  136.             targetXML = os.path.join(wpkgRoot,branch,'packages',sourceXML)
  137.             with open(targetXML,'w') as packageXML:
  138.                 packageXML.writelines(template.safe_substitute(d))
  139.  
  140. def check_local_update(msiDestination, version):
  141.     localfile = os.path.join(msiDestination, 'jdk', str(version),
  142.                              'localVersion.txt')
  143.  
  144.     try:
  145.         with open(localfile, 'r') as f:
  146.             lines = f.readlines()
  147.             update = int(lines[0])
  148.     except IOError:
  149.         update = 0
  150.     return int(update)
  151.  
  152. def write_local_update(msiDestination, version, update):
  153.     localVersionFile = os.path.join(msiDestination, 'jdk', str(version),
  154.                                     'localVersion.txt')
  155.     with open(localVersionFile, 'w') as f:
  156.         f.write(str(update))
  157.  
  158. if __name__ == "__main__":
  159.     version = 8
  160.     cookies = 'cookies.txt'
  161.     kinds = ["jdk", "jre"]
  162.     #wpkgRoot = r'\\some.server.fqdn\wpkg '[:-1]
  163.     wpkgRoot = r'c:\users\someuser\desktop\wpkg-tmp '[:-1]
  164.     msiDestination = wpkgRoot+r'\software '[:-1]
  165.     branches = [ 'dev', 'stable' ]
  166.  
  167.     print "Checking for latest update to Java %d" % (version)
  168.     update = find_latest_update(version = version)
  169.     print "It's update %s" % (update)
  170.     localUpdate = check_local_update(msiDestination = msiDestination,
  171.                                      version = version)
  172.     if localUpdate < update:
  173.         print "Local copy (%d) is out of date." % (localUpdate)
  174.         print "Making cookies"
  175.         make_cookies(cookies)
  176.         download_java(kinds = kinds,
  177.                       version = version,
  178.                       update = update,
  179.                       cookies = cookies)
  180.         copy_java_contents(kinds = kinds,
  181.                            version = version,
  182.                            update = update,
  183.                            msiDestination = msiDestination)
  184.         update_java_packages(kinds = kinds,
  185.                              version = version,
  186.                              update = update,
  187.                              wpkgRoot = wpkgRoot,
  188.                              branches = branches)
  189.         write_local_update(msiDestination = msiDestination,
  190.                            version = version, update = update)
  191.     else:
  192.         print "Local copy (%d) is current." % (localUpdate)
Advertisement
Add Comment
Please, Sign In to add comment