设为首页 收藏本站
查看: 2698|回复: 0

域环境通过powershell 远程修改本地管理员账户密码

[复制链接]

尚未签到

发表于 2018-9-2 13:29:50 | 显示全部楼层 |阅读模式
function Invoke-PasswordRoll  
{
  

  
    [CmdletBinding(DefaultParameterSetName="Encryption")]
  
    Param(
  
        [Parameter(Mandatory=$true)]
  
        [String[]]
  
        $ComputerName,
  

  
        [Parameter(Mandatory=$true)]
  
        [String[]]
  
        $LocalAccounts,
  

  
        [Parameter(Mandatory=$true)]
  
        [String]
  
        $TsvFileName,
  

  
        [Parameter(ParameterSetName="Encryption", Mandatory=$true)]
  
        [String]
  
        $EncryptionKey,
  

  
        [Parameter()]
  
        [ValidateRange(20,120)]
  
        [Int]
  
        $PasswordLength = 20,
  

  
        [Parameter(ParameterSetName="NoEncryption", Mandatory=$true)]
  
        [Switch]
  
        $NoEncryption
  
    )
  

  

  
#加载任何所需的 .net 类
  
    Add-Type -AssemblyName "System.Web" -ErrorAction Stop
  

  

  
#这是脚本块,将在 ComputerName 中指定的每台计算机上执行
  
    $RemoteRollScript = {
  
        Param(
  
            [Parameter(Mandatory=$true, Position=1)]
  
            [String[]]
  
            $Passwords,
  

  
            [Parameter(Mandatory=$true, Position=2)]
  
            [String[]]
  
            $LocalAccounts,
  

  
#在此处,我可以记录脚本所连接到的服务器名称,DNS 记录有时会变得很混乱,现在这样非常好。
  
            [Parameter(Mandatory=$true, Position=3)]
  
            [String]
  
            $TargettedServerName
  
        )
  

  
        $LocalUsers = Get-WmiObject Win32_UserAccount -Filter "LocalAccount=true" | Foreach {$_.Name}
  

  
#检查计算机是否具有密码不会由此脚本滚动的任何本地用户帐户
  
        foreach ($User in $LocalUsers)
  
        {
  
            if ($LocalAccounts -inotcontains $User)
  
            {
  
                Write-Warning "Server: '$($TargettedServerName)' has a local account '$($User)' whos password is NOT being changed by this script"
  
            }
  
        }
  

  
#对于此服务器中存在的所有指定的本地帐户,更改密码
  
        $PasswordIndex = 0
  
        foreach ($LocalAdmin in $LocalAccounts)
  
        {
  
            $Password = $Passwords[$PasswordIndex]
  

  
            if ($LocalUsers -icontains $LocalAdmin)
  
            {
  
                try
  
                {
  
                    $objUser = [ADSI]"WinNT://localhost/$($LocalAdmin), user"
  
                    $objUser.psbase.Invoke("SetPassword", $Password)
  

  
                    $Properties = @{
  
                        TargettedServerName = $TargettedServerName
  
                        Username =  $LocalAdmin
  
                        Password = $Password
  
                        RealServerName = $env:computername
  
                    }
  

  
                    $ReturnData = New-Object PSObject -Property $Properties
  
                    Write-Output $ReturnData
  
                }
  
                catch
  
                {
  
                    Write-Error "Error changing password for user:$($LocalAdmin) on server:$($TargettedServerName)"
  
                }
  
            }
  

  
            $PasswordIndex++
  
        }
  
    }
  

  

  
#在运行此脚本的客户端上生成密码,而非在远程计算机上。.NET 客户端配置文件中不提供 System.Web.Security。在运行该脚本的 # 客户端上进行此调用可确保只有 1 台计算机需要安装完整的 .NET 运行库(相对于已滚动密码的每个系统)。
  
    function Create-RandomPassword
  
    {
  
        Param(
  
            [Parameter(Mandatory=$true)]
  
            [ValidateRange(20,120)]
  
            [Int]
  
            $PasswordLength
  
        )
  

  
        $Password = [System.Web.Security.Membership]::GeneratePassword($PasswordLength, $PasswordLength / 4)
  

  
#此操作绝对不会失败,但不管怎样,我还是在这里加入了健全性检查
  
        if ($Password.Length -ne $PasswordLength)
  
        {
  
            throw new Exception("Password returned by GeneratePassword is not the same length as required. Required length: $($PasswordLength). Generated length: $($Password.Length)")
  
        }
  

  
        return $Password
  
    }
  

  

  
#主要功能 - 生成密码并通过远程方式进入计算机以更改指定的本地帐户的密码
  
    if ($PsCmdlet.ParameterSetName -ieq "Encryption")
  
    {
  
        try
  
        {
  
            $Sha256 = new-object System.Security.Cryptography.SHA256CryptoServiceProvider
  
            $SecureStringKey = $Sha256.ComputeHash([System.Text.UnicodeEncoding]::Unicode.GetBytes($EncryptionKey))
  
        }
  
        catch
  
        {
  
            Write-Error "Error creating TSV encryption key" -ErrorAction Stop
  
        }
  
    }
  

  
    foreach ($Computer in $ComputerName)
  
    {
  
#需要为每个帐户生成 1 个可以更改的密码
  
        $Passwords = @()
  
        for ($i = 0; $i -lt $LocalAccounts.Length; $i++)
  
        {
  
            $Passwords += Create-RandomPassword -PasswordLength $PasswordLength
  
        }
  

  
        Write-Output "Connecting to server '$($Computer)' to roll specified local admin passwords"
  
        $Result = Invoke-Command -ScriptBlock $RemoteRollScript -ArgumentList @($Passwords, $LocalAccounts, $Computer) -ComputerName $Computer
  
#如果正在使用加密,则在写入磁盘之前,使用用户提供的密钥对密码进行加密
  
        if ($Result -ne $null)
  
        {
  
            if ($PsCmdlet.ParameterSetName -ieq "NoEncryption")
  
            {
  
                $Result | Select-Object Username,Password,TargettedServerName,RealServerName | Export-Csv -Append -Path $TsvFileName -NoTypeInformation
  
            }
  
            else
  
            {
  
#筛选掉返回的 $null 条目
  
                $Result = $Result | Select-Object Username,Password,TargettedServerName,RealServerName
  

  
                foreach ($Record in $Result)
  
                {
  
                    $PasswordSecureString = ConvertTo-SecureString -AsPlainText -Force -String ($Record.Password)
  
                    $Record | Add-Member -MemberType NoteProperty -Name EncryptedPassword -Value (ConvertFrom-SecureString -Key $SecureStringKey -SecureString $PasswordSecureString)
  
                    $Record.PSObject.Properties.Remove("Password")
  
                    $Record | Select-Object Username,EncryptedPassword,TargettedServerName,RealServerName | Export-Csv -Append -Path $TsvFileName -NoTypeInformation
  
                }
  
            }
  
        }
  
    }
  
}function ConvertTo-CleartextPassword
  
{
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-561627-1-1.html 上篇帖子: 通过Enable-PSRemoting 开启Powershell远程管理失败的解决方法 下篇帖子: PowerShell基础系列
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表