Use powershell script to download windows patches monthly

本文介绍了一个PowerShell脚本,该脚本能够自动从微软RSS源抓取最新的安全公告,并下载对应的补丁文件。通过多级过滤,如产品名称、KB号等条件筛选出所需的补丁,有效减轻了手动更新的工作负担。

My company concerns security, request us to deploy the newest patches on our servers in time, even we have firewall/encryption internally.

Welcome email to: larry.song@outlook.com

With the number of servers increasing, there must be some servers can't be patched as expected, probably caused by SCCM/WSUS or incorrect configuration on server, plus 3rd party patch scanning software and presures from security team, support team like me have to patch missing patches one by one. This makes me have to paste the MS number in google, and find the correct KB, then download and install, turns out it's a mess.

To make life easier, I did the script to automatic download patches from MS with scheduled time, the script will grab contents from MS RSS and get MS numbers and links, it will loop MS links and grabs KBs, and download patches to local path.

Security RSS: https://technet.microsoft.com/en-us/security/rss/bulletin

Workflow: Get contents of RSS -> grab MS numbers and links -> Enum MS links and grab KBs -> filter out some KB -> grab KB details link -> grab KB download links -> Download

Step by step to analysis the script,

 

$Url = 'https://technet.microsoft.com/en-us/security/rss/bulletin'
$ExcludeProducts = 'lync|Itanium|for mac'
$IncludeProducts = 'server'

$ExcludePatches = '-IA64|Windows6\.0|-RT-|ServiceBusServer'

$PatchStoreTo = '.\'

some variables defined,

$Url is the link of RSS;

$ExcludeProducts when get the contents of MS link, use regular expression to filter out unwanted product, for me is lync and patches for Itanium cpu;

$IncludeProducts after product filter, i want to filter again for KBs for "server";

$ExcludePatches is another filter, when final get patch link, I don't want patches for Itanium (Why? because some KB doesn't have enough details, so this filter added);

$PatchStoreTo is a path to store patches.

 

$WebClient = New-Object System.Net.WebClient
$WebClient.Encoding = [System.Text.Encoding]::UTF8

Create the webclient object and set the encoding

 

do
{
    $RSSContent = $WebClient.DownloadString($Url)
}
while(
    $(if(!$?)
    {
        Write-Host 'Failed to get RSS' -ForegroundColor Red
        Start-Sleep -Seconds 600
        $true
    })
)

Get the contents of RSS, if failed, will report with red words and sleep 10 minutes to do again.

 

([xml]$RSSContent).rss.channel.Item | Sort-Object link | %{...}

Convert RSS contents to XML type, then can easily retrieve data.

 

    $MSRC_URL = $_.link
    Write-Host "Processing: [$MSRC_URL]" -ForegroundColor Yellow
    $MSRC = ([regex]::Match($MSRC_URL, '(?i)MS\d+-\d+$')).Value
    Write-Host "MS number: [$MSRC]" -ForegroundColor Green
    if(!(Test-Path -LiteralPath "$PatchStoreTo\$MSRC"))
    {
        do
        {
            New-Item -Path "$PatchStoreTo\$MSRC" -ItemType Directory | Out-Null
        }
        while(
            $(if(!$?)
            {
                Write-Host 'Failed to create MSRC folder' -ForegroundColor Red
                Start-Sleep 300
                $true
            })
        )
    }

MS link stores in $MSRC_URL, and output to screen as color yellow, then use regular expression to grab MS number and stored in $MSRC, after that create a folder named as MS number to store patches.

 

    Write-Host "Trying to capture KBs from MSRC URL" -ForegroundColor Yellow
    do
    {
        $MSContent = $null
        $MSContent = $WebClient.DownloadString($MSRC_URL)
    }
    while(
        $(if(!$?)
        {
            Write-Host 'Failed to capture MSRC content' -ForegroundColor Red
            Start-Sleep 300
            $true
        })
    )

Above codes is to grab MS link contents and store in $MSContent.

MS link is like https://technet.microsoft.com/en-us/library/security/MS14-063, MS contents are the source codes behind the web page.

 

[regex]::Matches($MSContent, '(?i)<tr>[\s\S]+?<a href="(http://www.microsoft.com/downloads/details.aspx\?FamilyID=[\w\-]+?)">[\s\S]+?\((\d{7})\)') | %{...}

The code is to grab KB information, like KB number, and KB link.

It will match contents like below screenshot, all characters in the grah will be matched by the regular expression pattern.

 

        Write-Host "KB: [$($_.Groups[2].Value)]" -NoNewline -ForegroundColor Green
        if($_.Value -imatch $ExcludeProducts)
        {
            Write-Host "   --- Excluded: [$($Matches[0])]" -ForegroundColor Red
        }
        else
        {
            if($_.Value -notmatch $IncludeProducts)
            {
                Write-Host "   --- Excluded: Not match [$IncludeProducts]" -ForegroundColor Red
                return
            }
            $KBNumber = "KB$($_.Groups[2].Value)"
       Write-Host "`nDownload URL: [$($_.Groups[1].Value)]" -ForegroundColor Gray

Above code excludes the KBs matched product names in $excludeProducts, and left KB filtered again by $IncludeProducts, final passed KBs store in $KBNumber.

 

            do
            {
                $KBContent = $null
                $KBContent = $WebClient.DownloadString($_.Groups[1].Value)
            }while(
                $(if(!$?)
                {
                    Write-Host 'Failed to capture KB content' -ForegroundColor Red
                    Start-Sleep 300
                    $true
                })
            )

Above code get contents from KB link and stores in $KBContent,

KB link looks like this in $MSContent: http://www.microsoft.com/downloads/details.aspx?familyid=8a59fc6d-cbad-4905-842b-e5aa1fc6fedf

Access KB link will automatic redirect to:http://www.microsoft.com/en-us/download/details.aspx?id=44400

Surely this is a automation behavior of web server, I don't need to do anything in the script. Anyway the KB link page doesn't contain patch link, it just ask for confimation on languages and provide us some KB details, you can find screenshot followed.

As followed, I need to analysis KB contents, and find the page called "confirmation.aspx". Actually I can see it when I move my cursor on the "Download" button.

 

            $KBConfirm = ([regex]::Match($KBContent, '(?i)href="(confirmation.aspx\?id=\d+)"')).Groups[1].Value
            $KBConfirm = "http://www.microsoft.com/en-us/download/$KBConfirm"
            Write-Host "KB confirm URL: [$KBConfirm]" -ForegroundColor Gray
            do
            {
                $KBContent = $null
                $KBContent = $WebClient.DownloadString($KBConfirm)
            }while(
                $(if(!$?)
                {
                    Write-Host 'Failed to capture KB download content' -ForegroundColor Red
                    Start-Sleep 300
                    $true
                })
            )

Codes used to grab "confirmation.aspx" page link from KB contents, you may find the "id" behind "confirmation.aspx" is the same like "details.aspx" of KB link, but just for safey, I choose to grab "confirmation.aspx" page from KB content.

 

            $KBLinks = @()
            $KBLinks = [regex]::Matches($KBContent, '(?i)<a href="(http://download.microsoft.com/download/.+?)".+?>Click here</span>') | %{
                $_.Groups[1].Value
            }
            $KBLinks = @($KBLinks | Sort-Object -Unique)
            Write-Host "The KB contains updates: [$($KBLinks.Count)]" -ForegroundColor Green

After I get the contents of "confirmation.aspx", I use regular expression to match patch links and do a unique sort for final results, now $KBLinks contains all patches belong to that KB.

Followed screenshot is the "confirmation.aspx", it contains all patches download link, I used regular expression again to grab those links.

 

            $KBLinks | %{
                $FileName = $null
                $FileName = $_.Split('/')[-1]
                if($FileName -imatch $ExcludePatches)
                {
                    Write-Host "Patch excluded: [$($Matches[0])]" -ForegroundColor Red
                    return
                }

Now I have patch links in hand, the job left is download, but I do another filter before the downloading, as i mentioned previously, sometimes KB contents don't have enough information, so in here I use another filter to remove patches i don't want by patch names.

 

                if(Test-Path -Path $FilePath)
                {
                    Write-Host 'File already exists, skip!' -ForegroundColor Gray
                }
                else
                {
                    do
                    {
                        $WebClient.DownloadFile($_, $FilePath)
                    }while(
                        $(if(!$?)
                        {
                            Write-Host 'Download file failed!' -ForegroundColor Red
                            Start-Sleep -Seconds 300
                            $true
                        })
                    )
                }

Real download codes here, if patch already exists, script will skip it.

 

Last, one screenshot when script running, and full script followed.

Full script here,

$Url = 'https://technet.microsoft.com/en-us/security/rss/bulletin'
$ExcludeProducts = 'lync|Itanium|for mac'
$IncludeProducts = 'server'

$ExcludePatches = '-IA64|Windows6\.0|-RT-|ServiceBusServer'

$PatchStoreTo = '.\'

$WebClient = New-Object System.Net.WebClient
$WebClient.Encoding = [System.Text.Encoding]::UTF8

do
{
    $RSSContent = $WebClient.DownloadString($Url)
}
while(
    $(if(!$?)
    {
        Write-Host 'Failed to get RSS' -ForegroundColor Red
        Start-Sleep -Seconds 600
        $true
    })
)

([xml]$RSSContent).rss.channel.Item | Sort-Object link | %{
    $MSRC_URL = $_.link
    Write-Host "Processing: [$MSRC_URL]" -ForegroundColor Yellow
    $MSRC = ([regex]::Match($MSRC_URL, '(?i)MS\d+-\d+$')).Value
    Write-Host "MS number: [$MSRC]" -ForegroundColor Green
    if(!(Test-Path -LiteralPath "$PatchStoreTo\$MSRC"))
    {
        do
        {
            New-Item -Path "$PatchStoreTo\$MSRC" -ItemType Directory | Out-Null
        }
        while(
            $(if(!$?)
            {
                Write-Host 'Failed to create MSRC folder' -ForegroundColor Red
                Start-Sleep 300
                $true
            })
        )
    }
    Write-Host "Trying to capture KBs from MSRC URL" -ForegroundColor Yellow
    do
    {
        $MSContent = $null
        $MSContent = $WebClient.DownloadString($MSRC_URL)
    }
    while(
        $(if(!$?)
        {
            Write-Host 'Failed to capture MSRC content' -ForegroundColor Red
            Start-Sleep 300
            $true
        })
    )
    
    [regex]::Matches($MSContent, '(?i)<tr>[\s\S]+?<a href="(https?://www.microsoft.com/downloads/details.aspx\?FamilyID=[\w\-]+?)">[\s\S]*?(\d{7})') | %{
        Write-Host "KB: [$($_.Groups[2].Value)]" -NoNewline -ForegroundColor Green
        if($_.Value -imatch $ExcludeProducts)
        {
            Write-Host "   --- Excluded: [$($Matches[0])]" -ForegroundColor Red
        }
        else
        {
            if($_.Value -notmatch $IncludeProducts)
            {
                Write-Host "   --- Excluded: Not match [$IncludeProducts]" -ForegroundColor Red
                return
            }
            $KBNumber = "KB$($_.Groups[2].Value)"
            Write-Host "`nDownload URL: [$($_.Groups[1].Value)]" -ForegroundColor Gray
<#
            if(!(Test-Path -Path "$MSRC\$KBNumber"))
            {
                do
                {
                    New-Item -Name "$MSRC\$KBNumber" -ItemType Directory | Out-Null
                }
                while(
                    $(if(!$?)
                    {
                        Write-Host 'Failed to create KB folder' -ForegroundColor Red
                        Start-Sleep 300
                        $true
                    })
                )
            }
#>
            do
            {
                $KBContent = $null
                $KBContent = $WebClient.DownloadString($_.Groups[1].Value)
            }while(
                $(if(!$?)
                {
                    Write-Host 'Failed to capture KB content' -ForegroundColor Red
                    Start-Sleep 300
                    $true
                })
            )

            $KBConfirm = ([regex]::Match($KBContent, '(?i)href="(confirmation.aspx\?id=\d+)"')).Groups[1].Value
            $KBConfirm = "http://www.microsoft.com/en-us/download/$KBConfirm"
            Write-Host "KB confirm URL: [$KBConfirm]" -ForegroundColor Gray
            do
            {
                $KBContent = $null
                $KBContent = $WebClient.DownloadString($KBConfirm)
            }while(
                $(if(!$?)
                {
                    Write-Host 'Failed to capture KB download content' -ForegroundColor Red
                    Start-Sleep 300
                    $true
                })
            )

            $KBLinks = @()
            $KBLinks = [regex]::Matches($KBContent, '(?i)<a href="(http://download.microsoft.com/download/.+?)".+?>Click here</span>') | %{
                $_.Groups[1].Value
            }
            $KBLinks = @($KBLinks | Sort-Object -Unique)
            Write-Host "The KB contains updates: [$($KBLinks.Count)]" -ForegroundColor Green
            $KBLinks | %{
                $FileName = $null
                $FileName = $_.Split('/')[-1]
                if($FileName -imatch $ExcludePatches)
                {
                    Write-Host "Patch excluded: [$($Matches[0])]" -ForegroundColor Red
                    return
                }
                $FilePath = $null
                $FilePath = "$MSRC\$FileName"
                Write-Host "Going to download file: [$FilePath]" -ForegroundColor Gray
                $FilePath = "$PatchStoreTo\$FilePath"
                if(Test-Path -Path $FilePath)
                {
                    Write-Host 'File already exists, skip!' -ForegroundColor Gray
                }
                else
                {
                    do
                    {
                        $WebClient.DownloadFile($_, $FilePath)
                    }while(
                        $(if(!$?)
                        {
                            Write-Host 'Download file failed!' -ForegroundColor Red
                            Start-Sleep -Seconds 300
                            $true
                        })
                    )
                }
            }
        }
    }
}

 

PS, about the proxy, WebClient class will use proxy settings on IE automatically, if want download patches via proxy, set IE to the right settings.

2015-03-02:Updated the regular expression for KB number capture, support for https link and fix capture for enclose.

转载于:https://www.cnblogs.com/LarryAtCNBlog/p/4026695.html

AI-PPT 一键生成 PPT:用户输入主题关键词,AI-PPT 可快速生成完整 PPT,涵盖标题、正文、段落结构等,还支持对话式生成,用户可在 AI 交互窗口边查看边修改。 文档导入转 PPT:支持导入 Word、Excel、PDF 等多种格式文档,自动解析文档结构,将其转换为结构清晰、排版规范的 PPT,有保持原文和智能优化两种模式。 AI-PPT 对话 实时问答:用户上传 PPT 或 PPTX 文件后,可针对演示内容进行提问,AI 实时提供解答,帮助用户快速理解内容。 多角度内容分析:对 PPT 内容进行多角度分析,提供全面视野,帮助用户更好地把握内容结构和重点。 多语言对话支持:支持多语言对话,打破语言障碍,方便不同语言背景的用户使用。 AI - 绘图 文生图:用户输入文字描述,即可生成符合语义的不同风格图像,如油画、水彩、中国画等,支持中英文双语输入。 图生图:用户上传图片并输入描述,AI - 绘图能够根据参考图和描述生成新的风格化图像,适用于需要特定风格或元素的创作需求。 图像编辑:提供如 AI 超清、AI 扩图、AI 无痕消除等功能,用户可以上传图片进行细节修改和优化,提升图片质量。 AI - 文稿 文案生成:能够根据用户需求生成多种类型的文章,如市场营销文案、技术文档、内部沟通内容等,提升文案质量和创作效率。 文章润色:对已有文章进行改善和优化,包括语言表达、逻辑连贯性、内容流畅度等方面,使文章更符合用户期望和风格。 文章续写:AI 技术理解文本语境,为用户提供新的想法、补充资料或更深层次的见解,帮助用户丰富文档内容。 AI - 医生 智能健康咨询:包括症状自查,用户输入不适症状,AI 结合病史等信息提供疾病可能性分析与初步建议;用药指导,支持查询药品适应症、禁忌症等,并预警潜在冲突;中医辨证,提供体质辨识与调理建议。 医学报告解读:用户上传体检报告
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值