如何从标准帐户以管理员身份运行VB.net命令?

时间:2015-12-29 14:34:26

标签: vb.net

有没有办法可以通过以标准用户身份登录系统,以管理员用户身份在我的系统上调用vb命令? 例如:运行程序从系统中删除只能通过管理员帐户完成的文件。

1 个答案:

答案 0 :(得分:3)

您可以使用以下内容以不同的用户身份运行进程:

Function ConvertToSecureString(ByVal str As String)
        Dim password As New SecureString
        For Each c As Char In str.ToCharArray
            password.AppendChar(c)
        Next
        Return password
End Function
Sub Main()
       dim username as string = "Administrator"
       dim password as SecureString = ConvertToSecureString("my password")
       dim domain as string = Nothing
       dim filename as string = "notepad.exe" ' %SYSTEMROOT%\system32
        Try
            System.Diagnostics.Process.Start(filename,username, password, domain)
        Catch ex As Win32Exception
            MessageBox.Show("Wrong username or password.", _
        "Error logging in as administrator", MessageBoxButtons.OK, _
         MessageBoxIcon.Error)
        End Try
End Sub

使用上述模式,您可以在假设的上下文中执行任何操作。例如,如果要删除文件,可以调用' cmd.exe / c del c:\ somefile.exe'。

您还可以使用较低级别的LogonUser P / Invoke / WindowsIdentity / WindowsImpersonationContext组合。

Imports System.Runtime.InteropServices
Imports System.Security.Principal


Module Module1

    Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal un As String, ByVal domain As String, ByVal pw As String, ByVal LogonType As Integer, ByVal LogonProvider As Integer,  ByRef Token As IntPtr) As Boolean

    Public Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Boolean

    Public Sub Main()
        Dim tokenHandle As New IntPtr(0)
        Try
            If LogonUser("un", "DOMAINNAME", "pw", 2, 0, tokenHandle) Then
                Dim newId As New WindowsIdentity(tokenHandle)
                Using impersonatedUser As WindowsImpersonationContext = newId.Impersonate()
                    'perform impersonated commands
                    System.IO.File.WriteAllText("C:ttestimp.txt", "test")
                End Using
                CloseHandle(tokenHandle)
            Else
                'logon failed
            End If
        Catch ex As Exception
            'exception
        End Try
    End Sub
End Module

更多信息1 / 2 / 3