65.9K
CodeProject 正在变化。 阅读更多。
Home

远程更改本地计算机用户密码

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (2投票s)

2013 年 10 月 11 日

CPOL

2分钟阅读

viewsIcon

10779

你是否想在 .net 中更改本地管理员帐户(或任何本地用户帐户)的密码?以下是如何操作:代码如下

你是否想在 .net 中更改本地管理员帐户(或任何本地用户帐户)的密码?以下是如何操作:代码背景为蓝色!

确保导入
System.DirectoryServices

Imports System.DirectoryServices


首先,我们需要检查计算机是否已启动,尝试快速 ping 一下


Dim pinger As New Net.NetworkInformation.Ping

试试

Dim result = pinger.Send(MachineName)

If result.Status <> Net.NetworkInformation.IPStatus.Success Then

'无法连接

Return False

End If

Catch ex As Exception

'无法连接

Return False

End Try


这很简单,你可以进一步增强它以提供一些反馈

现在连接到机器,使用
DirectoryEntry,它有很多参数/重载,但我们只对以下内容感兴趣

我们要连接的计算机地址
我们将用于更改密码的帐户用户名 - 必须具有更改本地用户密码的权限,因此如果你使用 AD 帐户,请确保它属于目标机器上的管理员组
上述帐户的密码
身份验证 - 如果连接不安全,机器将不允许你更改密码!

全部放在一起如下所示

Dim de As New DirectoryEntry(String.Format("WinNT://{0}", MachineName), "mydomain\accountname", " accountpassword", AuthenticationTypes.Secure)


快速检查是否有效

If de Is Nothing Then

'无法连接

Return False

End If


从技术上讲,你可以给它提供路径 WinNT://machinename/Nameoftheaccount,但我无法使其工作,总是抛出 80005000 错误,所以....

查询目录条目以找到我们要查找的帐户,在本例中:Administrator

Dim admin = de.Children.Find("Administrator")

If admin Is Nothing Then

'无法连接或找到帐户

Return False

End If



最后更改密码:请记住,密码必须符合你设置的任何复杂性要求!

试试

admin.Invoke("SetPassword", "New password")

admin.CommitChanges()

'完成!

Catch ex As Exception

Return False

End Try



完整的代码作为一个函数

Public Function ChangeLocalUserPassword(ByVal MachineName As String, ByVal LocalUser As String, ByVal Pass As String) As Boolean

Dim pinger As New Net.NetworkInformation.Ping

试试

Dim result = pinger.Send(MachineName)

If result.Status <> Net.NetworkInformation.IPStatus.Success Then

'无法连接

Return False

End If

Catch ex As Exception

Return False

End Try


Dim de As New DirectoryEntry(String.Format("WinNT://{0}", MachineName), "mydomain\accountname", " accountpassword", AuthenticationTypes.Secure)


If de Is Nothing Then

'无法连接或找到帐户

Return False

End If

Dim admin = de.Children.Find(LocalUser)


If admin Is Nothing Then

'无法连接或找到帐户

Return False

End If


试试

admin.Invoke("SetPassword", Pass)

admin.CommitChanges()

'完成!

Catch ex As Exception

Return False

End Try

End Function

 

© . All rights reserved.