Windows Account Management

windows account management

Recently deployed staff gave us a demand, it is hoped to simplify the deployment process.
In order to be able to control the remote desktop computer terminal, they need to set some settings for each terminal, for example, create a user name and password, open to allow
remote desktop settings, and the boot-free login settings, this part of the operation increased the workload of personnel deployed so if they propose to provide
a software installed on the terminal device a bit, then these settings are automatically set up, but also to support the modifications made behind the platform user name
function and password. With so explore these features, modify the registry section, use the registry comparison tool now sort out the results.
Create an administrator account

//传入参数:Username要创建的用户名,Userpassword用户密码,Path主文件夹路径 
public static bool CreateNTUser(string username, string userpassword, string path)
{
    try
    {
        DirectoryEntry obDirEntry = new DirectoryEntry("WinNT://" + Environment.MachineName);

        DirectoryEntry obUser = obDirEntry.Children.Add(username, "User"); //增加用户名 
        obUser.Properties["FullName"].Add(username); //用户全称 
        obUser.Invoke("SetPassword", userpassword); //用户密码 
        obUser.Invoke("Put", "Description", "远程用户");//用户详细描述 
        //obUser.Invoke("Put","PasswordExpired",1); //用户下次登录需更改密码 
        obUser.Invoke("Put", "UserFlags", 66049); //密码永不过期 
        obUser.Invoke("Put", "HomeDirectory", path); //主文件夹路径 
        obUser.CommitChanges();//保存用户 
        //DirectoryEntry grp = obDirEntry.Children.Find("Users", "group");//Users组 
        DirectoryEntry grp = obDirEntry.Children.Find("Administrators", "group");
        if (grp.Name != "")
        {
            grp.Invoke("Add", obUser.Path.ToString());//将用户添加到某组 
        }
        return true;
    }
    catch(Exception ex)
    {
        RGCommon.Log(ex.Message);
        return false;
    }
}

Delete Account

 //传入参数:Username用户名 
public static bool DelNTUser(string Username)
{
    try
    {
        DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
        DirectoryEntry obUser = localMachine.Children.Find(Username, "User");//找得用户 
        localMachine.Children.Remove(obUser);//删除用户 
        localMachine.Close();
        return true;
    }
    catch(Exception ex)
    {
        RGCommon.Log(ex.Message);
        return false;
    }
}

Rename Accounts

/// <summary>
/// 重命名账户
/// </summary>
/// <param name="username"></param>
/// <param name="newname"></param>
/// <returns></returns>
public static bool Rename(string username, string newname)
{
    try
    {
        DirectoryEntry localMachine = new DirectoryEntry($"WinNT://{Environment.MachineName},computer");
        DirectoryEntry obUser = localMachine.Children.Find(username, "User");
        obUser.Rename(newname);//重命名
        obUser.CommitChanges();
        obUser.Close();
        localMachine.Close();
        return true;
    }
    catch (Exception ex)
    {
        RGCommon.Log(ex.Message);
        return false;
    }
}

Change password

//修改NT用户密码 
//传入参数:Username用户名,Userpassword用户新密码 
public static bool InitNTPwd(string username, string userpassword)
{
    try
    {
        DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
        DirectoryEntry obUser = localMachine.Children.Find(username, "User");
        obUser.Invoke("SetPassword", userpassword);
        obUser.CommitChanges();
        obUser.Close();
        localMachine.Close();
        return true;
    }
    catch(Exception ex)
    {
        RGCommon.Log(ex.Message);
        return false;
    }
}

To determine whether the user exists

/// <summary>
/// 判断用户是否存在
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public static bool ExistWinUser(string userName)
{
    try
    {
        using(DirectoryEntry localMachine = new DirectoryEntry($"WinNT://{Environment.MachineName},computer"))
        {
            var user = localMachine.Children.Find(userName, "user");
            return user != null;
        }
    }
    catch(Exception ex)
    {
        RGCommon.Log(ex.Message);
    }
    return false;
}

Enable / disable account

 /// <summary>
/// 启用/禁用账户
/// </summary>
/// <param name="userName"></param>
/// <param name="isDisable"></param>
public static void Disable(string userName, bool isDisable)
{
    DirectoryEntry user = new DirectoryEntry($"WinNT://{Environment.MachineName}/{userName},user");
    user.InvokeSet("AccountDisabled", isDisable);
    user.CommitChanges();
    user.Close();
}

Inbound firewall rule added

/// <summary>
/// 添加入站规则
/// </summary>
/// <param name="name"></param>
/// <param name="port">要入站的端口号</param>
/// <param name="protocol"></param>
public static void NetFwAddPorts(string name, int port, string protocol)
{
    INetFwMgr netFwMgr = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr"));
    INetFwOpenPort objPort = (INetFwOpenPort)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwOpenPort"));
    objPort.Name = name;
    objPort.Port = port;
    if(protocol.ToUpper() == "TCP")
    {
        objPort.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
    }
    else
    {
        objPort.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP;
    }
    objPort.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
    objPort.Enabled = true;
    bool exist = false;
    //加入到防火墙管理策略
    foreach(INetFwOpenPort mPort in netFwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts)
    {
        if(objPort == mPort)
        {
            exist = true;
            break;
        }
    }
    if (!exist)
    {
        netFwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(objPort);
    }
}

Power-free login settings

/// <summary>
/// 免登陆设置
/// </summary>
public static void AutoAdminLogon(string userName, string password)
{
    Microsoft.Win32.RegistryKey root = Microsoft.Win32.RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, Microsoft.Win32.RegistryView.Registry64);
    Microsoft.Win32.RegistryKey item = root.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\", true);
    if(item != null)
    {
        item.SetValue("AutoAdminLogon", "1");
        item.SetValue("DefaultUserName", userName);
        item.SetValue("DefaultPassword", password);
    }
}

Allow Remote Desktop settings

/// <summary>
/// 允许远程桌面设置
/// </summary>
public static void AllowRemote()
{
    Microsoft.Win32.RegistryKey root = Microsoft.Win32.RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, Microsoft.Win32.RegistryView.Registry64);
    Microsoft.Win32.RegistryKey item = root.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Remote Assistance\", true);
    if(item != null)
    {
        item.SetValue("fAllowToGetHelp", "1");
    }
    item = root.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Terminal Server\", true);
    if(item != null)
    {
        item.SetValue("fDenyTSConnections", 0, Microsoft.Win32.RegistryValueKind.DWord);
    }
    item = root.OpenSubKey(@"SYSTEM\CurrentControlSet\services\SharedAccess\Parameters\FirewallPolicy\FirewallRules\", true);
    if(item != null)
    {
        item.SetValue("RemoteDesktop-In-TCP", "v2.10|Action=Allow|Active=TRUE|Dir=In|Protocol=6|LPort=3389|App=System|[email protected],-28753|[email protected],-28756|[email protected],-28752|");
    }
}

Guess you like

Origin www.cnblogs.com/zzr-stdio/p/11653165.html