• C# 改变Windows中服务的登录身份 (账户名和密码)


    在 C# 中,我们可以使用 WMI 类中的 Win32_Service 或者 Win32 API 中的函数 ChangeServiceConfig 来修改本地或远程计算机 Windows 服务登录身份 (账户) 的用户名和密码。

     1、使用 Win32 API 修改服务登录身份信息:

    使用 Win32 API 中的函数 ChangeServiceConfig 更改的是服务控制管理器数据库中指定服务的配置信息。

    private const int SC_MANAGER_ALL_ACCESS = 0x000F003F;
    private const uint SERVICE_NO_CHANGE = 0xffffffff;  //这个值可以在 winsvc.h 中找到
    private const uint SERVICE_QUERY_CONFIG = 0x00000001;
    private const uint SERVICE_CHANGE_CONFIG = 0x00000002;
     
    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    public static extern Boolean ChangeServiceConfig(IntPtr hService, UInt32 nServiceType, 
        UInt32 nStartType,UInt32 nErrorControl,String lpBinaryPathName,String lpLoadOrderGroup,
        IntPtr lpdwTagId, [In] char[] lpDependencies, String lpServiceStartName, 
        String lpPassword, String lpDisplayName);
     
    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, uint dwDesiredAccess);
     
    [DllImport("advapi32.dll", EntryPoint = "OpenSCManagerW", ExactSpelling = true, 
        CharSet = CharSet.Unicode, SetLastError = true)]
    public static extern IntPtr OpenSCManager(string machineName, string databaseName, uint dwAccess);
     
    public static bool ChangeServiceAccountInfo(string serviceName, string username,string password)
    {
        try
        {
            IntPtr scm_Handle = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS);
            if (scm_Handle == IntPtr.Zero)
              throw new System.Runtime.InteropServices.ExternalException("打开服务管理器错误");
     
            IntPtr service_Handle = OpenService(scm_Handle, serviceName,SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG);
            if (service_Handle == IntPtr.Zero)
              throw new System.Runtime.InteropServices.ExternalException("打开服务错误");
    //修改服务的账户用户名和密码 if (!ChangeServiceConfig(service_Handle, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE, null, null, IntPtr.Zero, null, username, password, null)) { int nError = Marshal.GetLastWin32Error(); Win32Exception win32Exception = new Win32Exception(nError); throw new System.Runtime.InteropServices.ExternalException("无法修改服务登录身份的用户名和密码:" + win32Exception.Message); } Console.WriteLine("服务登录身份信息修改成功!"); return true; } catch (Exception ex) { Console.WriteLine(ex.ToString()); return false; } }

     2、使用 C# 中 WMI 修改服务登录身份信息:

    使用 WMI 服务,我们需要添加 System.Management 的引用。

    注意:如果您的远程计算机连接的是 Active Directory 域,那么使用完全限定的用户名(例如 TestDomainMorgan)而不是简单的用户名(Morgan)。

    using System.Management;
    
    public static void ChangeServiceAccountInfobyWMI(string serviceName, string username, string password)
    {
        string mgmntPath = string.Format("Win32_Service.Name='{0}'", serviceName);
        using (ManagementObject service = new ManagementObject(new ManagementPath(mgmntPath)))
        {
            object[] accountParams = new object[11];
            accountParams[6] = username;
            accountParams[7] = password;
            uint returnCode = (uint)service.InvokeMethod("Change", accountParams);
            if (returnCode == 0)
            {
                 Console.WriteLine("服务登录身份信息修改成功!");
            }
            else
            {
                 Console.WriteLine("服务登录身份信息修改失败");
                 Console.WriteLine("错误代码:" + returnCode);
                 // 此微软官方支持链接,可以查看相应的返回代码的消息:
                 // https://msdn.microsoft.com/en-us/library/aa393660(v=vs.85).aspx
            }
        }
    }

     3、使用 C#中的 WMI 修改远程计算机服务的登录身份信息:

    使用 WMI 服务,我们需要添加 System.Management 的引用,并且在修改远程计算机中的服务信息时,请使用管理员凭据。

    注意:如果您的远程计算机连接的是 Active Directory 域,那么使用完全限定的用户名(例如 TestDomainMorgan)而不是简单的用户名(Morgan)。

    using System.Management;
    static void ChangeRemoteServiceAccountInfo(string remoteComputer, string serviceName, string username, string password) { try { ConnectionOptions connectionOptions = new ConnectionOptions(); // 如需要,请使用证书 //connectionOptions.Username = "Administrator"; //connectionOptions.Password = "AdminPassword"; //connectionOptions.Impersonation = ImpersonationLevel.Impersonate; ManagementScope scope = new ManagementScope("" + remoteComputer + "rootCIMV2", connectionOptions); scope.Connect(); string mgmntPath = string.Format("Win32_Service.Name='{0}'", serviceName); using (ManagementObject service = new ManagementObject(scope, new ManagementPath(mgmntPath),new ObjectGetOptions())) { object[] accountParams = new object[11]; accountParams[6] = username; accountParams[7] = password; uint returnCode = (uint)service.InvokeMethod("Change", accountParams); if (returnCode == 0) { Console.WriteLine("服务登录身份信息修改成功!"); } else { Console.WriteLine("服务登录身份信息修改失败"); Console.WriteLine("错误代码:" + returnCode); // 此微软官方支持链接,可以查看相应的返回代码信息: // https://msdn.microsoft.com/en-us/library/aa393660(v=vs.85).aspx } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }

    原创出处:https://morgantechspace.com/2015/03/csharp-change-service-account-username-and-password.html

  • 相关阅读:
    socket 编程
    空间配置器
    线程
    Linux系统编程——进程替换:exec 函数族
    linux粘着位
    exit函数与_exit
    [smart210] 定时器与PWM
    [smart210] s5pv210的中断体系
    [smart210] Nand Flash K9F4G08U0B 的配置与读写控制(二)
    [smart210] Nand Flash K9F4G08U0B 的配置与读写控制(一)
  • 原文地址:https://www.cnblogs.com/seanyan/p/13167028.html
Copyright © 2020-2023  润新知