【问题标题】:Downloading jdk using powershell使用powershell下载jdk
【发布时间】:2014-08-17 06:48:47
【问题描述】:

我正在尝试使用下面链接中给出的 powershell 脚本下载 java jdk

http://poshcode.org/4224

。正如作者所指定的,如果我更改存在最新 jdk 的源 url 即,

http://download.oracle.com/otn-pub/java/jdk/8u5-b13/jdk-8u5-windows-x64.exe

内容没有被加载,只有大约 6KB 被下载。我有一个疑问,powershell脚本的下载限制是否只有6KB?

代码如下:

$source = "http://download.oracle.com/otn-pub/java/jdk/8u5-b13/jdk-8u5-windows-i586.exe"
      $destination = "C:\Download\Java\jdk-7u60-windows-i586.exe"
      $client = new-object System.Net.WebClient
      $client.DownloadFile($source, $destination)

【问题讨论】:

  • 作者可能不是从oracle网站下载的...

标签: java powershell powershell-2.0


【解决方案1】:

在检查 oracle 站点上的会话时,以下 cookie 引起注意:oraclelicense=accept-securebackup-cookie。考虑到这一点,您可以运行以下代码:

$source = "http://download.oracle.com/otn-pub/java/jdk/8u5-b13/jdk-8u5-windows-i586.exe"
$destination = "C:\Download\Java\jdk-7u60-windows-i586.exe"
$client = new-object System.Net.WebClient 
$cookie = "oraclelicense=accept-securebackup-cookie"
$client.Headers.Add([System.Net.HttpRequestHeader]::Cookie, $cookie) 
$client.downloadFile($source, $destination)

【讨论】:

  • Exception calling "DownloadFile" with "2" argument(s): "An exception occurred during a WebClient request." At line:1 char:1 + $client.downloadFile($source, $destination) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : WebException
  • 嘿@MatasVaitkevicius,如果你提出一个单独的问题会更好 - 原来的帖子已经将近6年了......
【解决方案2】:

编辑:这是您的问题的原因:您不能在没有接受条款之前直接下载文件。

我正在使用以下脚本下载文件。它与 HTTP 以及 FTP 一起使用。这对您的任务来说可能有点矫枉过正,因为它还会显示下载进度,但您可以对其进行修剪,直到它适合您的需要为止。

param(
    [Parameter(Mandatory=$true)]
    [String] $url,
    [Parameter(Mandatory=$false)]
    [String] $localFile = (Join-Path $pwd.Path $url.SubString($url.LastIndexOf('/'))) 
)

begin {
    $client = New-Object System.Net.WebClient
    $Global:downloadComplete = $false

    $eventDataComplete = Register-ObjectEvent $client DownloadFileCompleted `
        -SourceIdentifier WebClient.DownloadFileComplete `
        -Action {$Global:downloadComplete = $true}
    $eventDataProgress = Register-ObjectEvent $client DownloadProgressChanged `
        -SourceIdentifier WebClient.DownloadProgressChanged `
        -Action { $Global:DPCEventArgs = $EventArgs }    
}

process {
    Write-Progress -Activity 'Downloading file' -Status $url
    $client.DownloadFileAsync($url, $localFile)

    while (!($Global:downloadComplete)) {                
        $pc = $Global:DPCEventArgs.ProgressPercentage
        if ($pc -ne $null) {
            Write-Progress -Activity 'Downloading file' -Status $url -PercentComplete $pc
        }
    }

    Write-Progress -Activity 'Downloading file' -Status $url -Complete
}

end {
    Unregister-Event -SourceIdentifier WebClient.DownloadProgressChanged
    Unregister-Event -SourceIdentifier WebClient.DownloadFileComplete
    $client.Dispose()
    $Global:downloadComplete = $null
    $Global:DPCEventArgs = $null
    Remove-Variable client
    Remove-Variable eventDataComplete
    Remove-Variable eventDataProgress
    [GC]::Collect()    
}

【讨论】:

  • 感谢代码,但不幸的是它没有下载完整的 exe,只下载了 6KB。我使用的网址是:download.oracle.com/otn-pub/java/jdk/8u5-b13/…
  • 这就是我打开 URL 时遇到的问题:对不起!要从 Oracle 技术网下载产品,您必须同意 OTN 许可条款。请确保... 您的浏览器启用了“cookies”和 JavaScript。您为要下载的产品单击了“接受许可”。您在接受许可后 30 分钟内尝试下载。从这里你可以去... 返回上一页 站点地图 OTN 主页
  • 所以这就是你的问题的原因:你不能在不接受之前的条款的情况下直接下载文件。
  • 但现在我确定问题出在条款协议上。如果您保存错误网站,它的大小与您正在下载的文件的大小完全相同。您甚至可以将下载的文件从 .exe 重命名为 .html 并在浏览器中打开。
  • 有一个想法,但它很脏。您可以使用 JMeter 之类的工具来记录 HTTP 调用的宏,从而引导您接受下载条款,并尝试通过直接发送 HTTP 请求来重现路径。不知道它是否有效。
【解决方案3】:

在需要 JDK 作为依赖项的平台安装程序需要此脚本后:

<# Config #>
$DownloadPageUri = 'https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html';
$JavaVersion = '8u201';

<# Build the WebSession containing the proper cookie 
   needed to auto-accept the license agreement. #>
$Cookie=New-Object -TypeName System.Net.Cookie; 
$Cookie.Domain='oracle.com';
$Cookie.Name='oraclelicense';
$Cookie.Value='accept-securebackup-cookie'; 
$Session= `
   New-Object -TypeName Microsoft.PowerShell.Commands.WebRequestSession;
$Session.Cookies.Add($Cookie);

<# Fetch the proper Uri and filename from the webpage. #>
$JdkUri = (Invoke-WebRequest -Uri $DownloadPageUri -WebSession $Session -UseBasicParsing).RawContent `
    -split "`n" | ForEach-Object { `
        If ($_ -imatch '"filepath":"(https://[^"]+)"' { `
            $Matches[1] `
        } `
    } | Where-Object { `
        $_ -like "*-$JavaVersion-windows-x64.exe" `
    }[0];
If ($JdkUri -imatch '/([^/]+)$') { 
    $JdkFileName=$Matches[1];
}

<# Use a try/catch to catch the 302 moved temporarily 
   exception generated by oracle from the absance of
   AuthParam in the original URL, piping the exception's
   AbsoluteUri to a new request with AuthParam returned
   from Oracle's servers.  (NEW!) #>

try { 
    Invoke-WebRequest -Uri $JdkUri -WebSession $Session -OutFile "$JdkFileName"
} catch { 
    $authparam_uri = $_.Exception.Response.Headers.Location.AbsoluteUri;
    Invoke-WebRequest -Uri $authparam_uri -WebSession $Session -OutFile "$JdkFileName"
} 

在 PowerShell 6.0 中工作(Hello 2019!)需要对正则表达式和 -imatch 行扫描的方式进行小幅修复。遵循 302 重定向的解决方法位于此处:https://github.com/PowerShell/PowerShell/issues/2896(fcabralpacheco 重新调整了 302 重定向解决方法以使 Oracle 下载再次正常工作!

此解决方案自动下载适用于 Windows x64 的 8u201。

【讨论】:

    【解决方案4】:

    由于接受的评论不再有效,我无法发表评论,我将把我的方法留在这里。我修改了@steve-coleman 的答案,使其扫描页面以查找以https 而不是http 开头的下载链接。我还需要修改$Response 以拥有-UseBasicParsing 标志,因为我使用的是无头Windows Server。总而言之,我使用的脚本是:

    $DownloadPageUri = 'http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html'
    $JavaVersion = '8u192'
    
    $Response = Invoke-WebRequest -Uri $DownloadPageUri -UseBasicParsing
    
    $JreUri = @($Response.RawContent -split "`n" | ForEach-Object {If ($_ -imatch '"filepath":"(https://[^"]+)"') {$Matches[1]}} | Where-Object {$_ -like "*-$JavaVersion-windows-x64.tar.gz"})
    If (-Not $JreUri.Count -eq 1) {
        throw ('Expected to retrieve only one URI but got {0}' -f $JreUri.Count)
    }
    
    If ($JreUri[0] -imatch '/([^/]+)$') {
        $JreFileName = $Matches[1]
    }
    $JreFileName = 'jre-windows-x64.tar.gz'
    
    If (-Not (Test-Path -Path "$PSScriptRoot\$JreFileName") -Or -Not (Test-Path -Path "$PSScriptRoot\Java-$JavaVersion.tag")) {
        $Cookie  = New-Object -TypeName System.Net.Cookie
        $Cookie.Domain = 'oracle.com'
        $Cookie.Name   = 'oraclelicense'
        $Cookie.Value  = 'accept-securebackup-cookie'
        $Session = New-Object -TypeName Microsoft.PowerShell.Commands.WebRequestSession
        $Session.Cookies.Add($Cookie)
        Invoke-WebRequest -Uri $JreUri[0] -WebSession $Session -OutFile "$PSScriptRoot\$JreFileName"
        New-Item -Path "$PSScriptRoot\Java-$JavaVersion.tag" -ItemType File | Out-Null
    }
    

    像往常一样,YMMV,特别是如果 Oracle 更改他们的网站。

    【讨论】:

      【解决方案5】:

      我将 Robert Smith 的答案修改如下以获得 SDK 8u211

      <# Config #>
      $DownloadPageUri = 'https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html';
      $JavaVersion = '8u211';
      <# Build the WebSession containing the proper cookie
         needed to auto-accept the license agreement. #>
      
      $Cookie=New-Object -TypeName System.Net.Cookie;
      $Cookie.Domain='oracle.com';
      $Cookie.Name='oraclelicense';
      $Cookie.Value='accept-securebackup-cookie';
      $Session= `
         New-Object -TypeName Microsoft.PowerShell.Commands.WebRequestSession;
      $Session.Cookies.Add($Cookie);
      
      # Fetch the proper Uri and filename from the webpage. #>
      $i = 0
      #echo $i
      #$rc = (Invoke-WebRequest -Uri $DownloadPageUri -WebSession $Session     -UseBasicParsing).RawContent
      #echo $rc >> Oracle.html
      #-split "`n" | ForEach-Object { `
      $JdkUri = (Invoke-WebRequest -Uri $DownloadPageUri -WebSession $Session -UseBasicParsing).RawContent `
      -split '\r?\n' | ForEach-Object { `
          #echo "$i : $_" >> Oracle.html
          #echo "$i"
          #$i++
          If ($_ -imatch '"filepath":"(https://[^"]+)"') { `
              $Matches[1] `
          } `
      } | Where-Object { `
          $_ -like "*-$JavaVersion-windows-x64.exe" `
      }[0];
      If ($JdkUri -imatch '/([^/]+)$') {
          $JdkFileName=$Matches[1];
      }
      echo "JdkUri: $JdkUri" >> out.txt
      
      <# Use a try/catch to catch the 302 moved temporarily
         exception generated by oracle from the absance of
         AuthParam in the original URL, piping the exception's
         AbsoluteUri to a new request with AuthParam returned
         from Oracle's servers.  (NEW!) #>
      
      try {
          echo "In the try" >> out.txt
          Invoke-WebRequest -Uri $JdkUri -WebSession $Session -OutFile "$JdkFileName"
      } catch {
          echo "In the catch" >> out.txt
          $authparam_uri = $_.Exception.Response.Headers.Location.AbsoluteUri;
          Invoke-WebRequest -Uri $authparam_uri -WebSession $Session -OutFile "$JdkFileName"
      }
      

      不得不换行 -拆分“n" | ForEach-Object { 到 -split '\r?\n' | ForEach-Object { `

      还有那行 if ($_ -imatch '"filepath":"(https://[^"]+)"' { to If ($_ -imatch '"filepath":"(https://[^"]+)"') {

      但是在 jkd-8u211-windows-x64.exe 文件中我看到了

      <html>
      <script language="javascript" type="text/javascript">
      function submitForm()
      {
          var hash = location.hash;
          if (hash) {
              if(hash.indexOf("#") == -1){
                  hash="#"+hash
              }
              document.myForm.action = document.myForm.action+hash;
          }
          document.myForm.submit();
      }
      </script><head><base target="_self"></head><body onLoad="submitForm()"><noscript>       <p>JavaScript is required. Enable JavaScript to use OAM Server.</p></noscript><form   action="https://login.oracle.com/mysso/signon.jsp" method="post" name="myForm"> <!------------ DO NOT REMOVE -------------><!----- loginform renderBrowserView -----><!-- Required for SmartView Integration --><input type="hidden" name="bmctx" value="05C65B855F507509F2A50E4187F746B908003F815E8CAC65124394831AC5D9EF"><input type="hidden" name="contextType" value="external"><input type="hidden" name="username" value="string"><input type="hidden" name="contextValue" value="%2Foam"><input type="hidden" name="password" value="secure_string"><input type="hidden" name="challenge_url" value="https%3A%2F%2Flogin.oracle.com%2Fmysso%2Fsignon.jsp"><input type="hidden" name="request_id" value="-7095362132919578964"><input type="hidden" name="authn_try_count" value="0"><input type="hidden" name="OAM_REQ" value="VERSION_4~FWMjicP9PEQpljiEhsObqw9ylPjCAidBVTTJxhmD1hxQnGA4pyWKyCqsJWbqRCHi7qV9ZGSvNoA5t9c33sgIg2B%2bVMyE%2b7Ev3v%2f0UWTE5TDtvGOxisL8d7gDA5piF4HZHubed6GfNVCktpGfz0y7KW0roRz3%2b58adfBEomJffDOl1UAkCDbV%2b7712R6CjE6nfODUMJTFUJ6nc9Zq6%2fuooydHQx9GjTeD6RBSlDo2L2b0KDi5g1exggoqrUMintE3QRbymUgvxkJyVAoxC%2bo8xLDF4EOICI0vkYnovHUNN%2bNoiQLGWXv1ryOuFy9FIebX%2bA5uxiDbulaRSDQcGO1LefWYF%2bBP7Vo3wRcNb%2bgc8J9%2fRjGVlKQSETLkUXd%2fo0U7cEPFSrq1qOmE6B7yKkB3zFnIsxHELMwdhVD5WJ95xebDem9xlhv61ImKJH3JdrnnDYZ3e3S1v90epLpFQyG1BExZxc%2fVLQZt%2bAexfGNstpqmlCFnfuC4Xudh0omOLAz5ZCdeWReNh0rC%2f0jXLEAkq6DghomBCNI5pGVKH1CVgb13HZOS%2boOuCaz4nw%2fAkkS949FW8Mzj0P9Cll7AlbTwfLu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iiEgJDfcLsRYDVa4amcR6uUo2E3GueUa4KXXH6XZQg%2fvH6JmzvP%2bLIKx%2fyMWf6JuKdi6w6P34VTBPLi1o9rQVTeIMQB0NsvQWowWcZEm1eGLC1Q%2fVJFMUHTCF9S75hL%2bYSve%2blE2JKf4Fbxp%2fAEGsuHmfRNu8lWHzaNuuFRZwl0mt8OnnmPAhOYpb1fvqkGLQfFRRYF1H7S1zFcTGeFalXa9FeuAQ31xglHgoXYni6TJOSQWbKAEiyh6YjwPza2U0hcaS%2fLbJwblHbhx8dko3My7kED75iKKmfUsvWO%2fxE93ngbP%2bNC8vs7KVzKyJhoKamHYykXfqWCWlCAz%2fyzo2GgU1ZAIdTHQOrysMnTIZxQvm9oOK8egdTbrweyHjsLYNGvA8LbmutI8%2fbtAD5BS9IE02qL2YtmI3nT39srKW%2b8JEP727dtLDGPaFJGDmfszhXZu1elSKEOUa62O8QoIjt5znJaVfJgh3sNrvj6VgGj3WGZf5EVMeD6LUdrQEtv8G3ZIkL1p%2f3qBSlgDjEPjDcTUJtEYNjuly7FNyBq2ZEgwvIjXIB8Q8nId%2b1QPOygTfkM5gqFlK2tG0sRpZEIh6J9Ov1IsgKBTBvfGvGuwI3REk2WXMkt78l7JrS3zvQoXpbM4e724JosN7LnrLQ%2bxn%2f6Ofy4RGNDza9FpGkcXea9%2b5%2fnNEKDNaYl3hZiTS2YxYTDFSKkotkadA3BJBse9dMF1cC5bj3IKgiNrTgSpHOvZbIEVi7bRJg7x66lzWWuellSEd%2bZYpIdxdBqUGrF7KehTh%2fHsjG5T5678e%2fuT8Uvm9S7bmE6xY3tBlQ2aO5FKWIA%3d%3d"><input type="hidden" name="locale" value="en"><input type="hidden" name="resource_url" value="https%253A%252F%252Fedelivery.oracle.com%252Fakam%252Fotn%252Fjava%252Fjdk%252F8u211-b12%252F478a62b7d4e34b78b671c754eaaf38ab%252Fjdk-8u211-windows-x64.exe"></form></body>    </html>
      

      不知道下一步该做什么。 还添加了一些调试爵士乐,例如 #echo "$i : $_" >> Oracle.html ...

      【讨论】:

        【解决方案6】:

        我在这里得到了这个,所有的功劳都归功于他...... http://dille.name/blog/2016/06/21/running-minecraft-in-a-windows-container-using-docker/

        https://github.com/nicholasdille/docker

        它可以工作并下载 Java 文件。

        $DownloadPageUri = 'http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html'
        $JavaVersion = '8u172'
        
        $Response = Invoke-WebRequest -Uri $DownloadPageUri
        
        $JreUri = @($Response.RawContent -split "`n" | ForEach-Object {If ($_ -imatch '"filepath":"(http://[^"]+)"') {$Matches[1]}} | Where-Object {$_ -like "*-$JavaVersion-windows-x64.tar.gz"})
        If (-Not $JreUri.Count -eq 1) {
            throw ('Expected to retrieve only one URI but got {0}' -f $JreUri.Count)
        }
        
        If ($JreUri[0] -imatch '/([^/]+)$') {
            $JreFileName = $Matches[1]
        }
        $JreFileName = 'jre-windows-x64.tar.gz'
        
        If (-Not (Test-Path -Path "$PSScriptRoot\$JreFileName") -Or -Not (Test-Path -Path "$PSScriptRoot\Java-$JavaVersion.tag")) {
            $Cookie  = New-Object -TypeName System.Net.Cookie
            $Cookie.Domain = 'oracle.com'
            $Cookie.Name   = 'oraclelicense'
            $Cookie.Value  = 'accept-securebackup-cookie'
            $Session = New-Object -TypeName Microsoft.PowerShell.Commands.WebRequestSession
            $Session.Cookies.Add($Cookie)
            Invoke-WebRequest -Uri $JreUri[0] -WebSession $Session -OutFile "$PSScriptRoot\$JreFileName"
            New-Item -Path "$PSScriptRoot\Java-$JavaVersion.tag" -ItemType File | Out-Null
        }
        

        【讨论】:

        • 我不确定是谁投了反对票。但它工作正常。检查 DownloadPageUri、javaversion 和 JavaVersion-windows-x64.tar.gz 是否仍然有效。如果 oracle 更改任何内容,这将停止工作。
        • 尝试设置 $JavaVersion = '8u191',每次更新版本信息时都会中断。
        猜你喜欢
        • 2016-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-06
        相关资源
        最近更新 更多