如何使用.NET操作本地用户组和用户(2006年博客迁移)

ContractedBlock.gif ExpandedBlockStart.gif 代码

   
using System;
using System.IO;
using System.Windows.Forms;
using System.Collections;
using System.Xml;
using System.Runtime.InteropServices;
// **********************************************************************
// ** Create By: 熊鹰
// ** Create Date: 2006-07-20
// ** Description: 操作本地用户和组的类
// ** Modify List:
// **********************************************************************
namespace LocalGroupUserTest
{
/// <summary>
/// ------------------熊鹰的测试代码 ------------------
/// LocalGroupUserHelper helper=new LocalGroupUserHelper();
/// helper.AddUser(null,"Test","1","Test User Comments");
/// helper.RemoveUser(null,"Test");
/// helper.UpdateUser(null,"Test");
/// helper.ModifyUserPassword(null,"Test","1","11");
/// helper.GetUserInfo(null,"Test");
/// helper.GetAllUserInfo(null);
/// helper.UserInLocalGroups(null,"Test");
///
/// helper.AddGroup(null,"Tests","Tests Group Comments");
/// helper.GroupAddMembers(null,"Tests","kevin\\Administrator");
///
/// 下面的代码中,因为时间的关系,我只写了有关创建本地组、将用户添加到某本地组、添加、删除、修改某本地用户等方法。
/// 如果,项目业务需求中有更多的功能要求,请自行扩展相关代码。
/// 下面的代码中主要引用Win32库"Netapi32.dll",相关函数和结构如下(更详细的信息请参考MSDN):
/// NetUserAdd
/// NetUserChangePassword
/// NetUserDel
/// NetUserEnum
/// NetUserGetGroups
/// NetUserGetInfo
/// NetUserGetLocalGroups
/// NetUserModalsGet
/// NetUserModalsSet
/// NetUserSetGroups
/// NetUserSetInfo
/// NetValidateName
/// NetValidatePasswordPolicy
/// NetValidatePasswordPolicyFree
/// USER_INFO_0
/// USER_INFO_1
///
/// NetLocalGroupAdd
/// NetLocalGroupAddMember
/// NetLocalGroupAddMembers
/// NetLocalGroupDel
/// NetLocalGroupDelMember
/// NetLocalGroupDelMembers
/// NetLocalGroupEnum
/// NetLocalGroupGetInfo
/// NetLocalGroupGetMembers
/// NetLocalGroupSetInfo
/// NetLocalGroupSetMembers
/// LOCALGROUP_INFO_0
/// LOCALGROUP_INFO_1
/// LOCALGROUP_INFO_1002
/// LOCALGROUP_MEMBERS_INFO_0
/// LOCALGROUP_MEMBERS_INFO_1
/// LOCALGROUP_MEMBERS_INFO_2
/// LOCALGROUP_MEMBERS_INFO_3
/// LOCALGROUP_USERS_INFO_0
/// ……
public class LocalGroupUserHelper
{
[DllImport(
" Netapi32.dll " )]
extern static int NetUserAdd([MarshalAs(UnmanagedType.LPWStr)] string servername, int level, ref USER_INFO_1 buf, int parm_err);

[DllImport(
" Netapi32.dll " )]
extern static int NetLocalGroupAdd([MarshalAs(UnmanagedType.LPWStr)] string servername, int level, ref LOCALGROUP_INFO_1 buf, int parm_err);

[DllImport(
" Netapi32.dll " )]
extern static int NetLocalGroupAddMembers([MarshalAs(UnmanagedType.LPWStr)] string servername, [MarshalAs(UnmanagedType.LPWStr)] string groupname,
int level, ref LOCALGROUP_MEMBERS_INFO_3 buf, int totalentries);

[StructLayout(LayoutKind.Sequential, CharSet
= CharSet.Unicode)]
public struct LOCALGROUP_MEMBERS_INFO_3
{
public string domainandname; // <DomainName>\<AccountName> // lgrmi3_domainandname
}

[DllImport(
" Netapi32.dll " )]
extern static int NetUserDel([MarshalAs(UnmanagedType.LPWStr)] string servername, [MarshalAs(UnmanagedType.LPWStr)] string username);

[DllImport(
" Netapi32.dll " )]
extern static int NetUserGetInfo([MarshalAs(UnmanagedType.LPWStr)] string servername, [MarshalAs(UnmanagedType.LPWStr)] string username, int level, out IntPtr bufptr);

[DllImport(
" Netapi32.dll " )]
extern static int NetUserSetInfo([MarshalAs(UnmanagedType.LPWStr)] string servername, [MarshalAs(UnmanagedType.LPWStr)] string username, int level, ref USER_INFO_1 buf, int error);

[DllImport(
" Netapi32.dll " )]
extern static int NetUserChangePassword([MarshalAs(UnmanagedType.LPWStr)] string domainname, [MarshalAs(UnmanagedType.LPWStr)] string username, [MarshalAs(UnmanagedType.LPWStr)] string oldpassword, [MarshalAs(UnmanagedType.LPWStr)] string newpassword);

[StructLayout(LayoutKind.Sequential, CharSet
= CharSet.Unicode)]
public struct USER_INFO_0
{
public String Username;
}

[DllImport(
" Netapi32.dll " )]
extern static int NetUserEnum([MarshalAs(UnmanagedType.LPWStr)] string servername, int level, int filter, out IntPtr bufptr, int prefmaxlen, out int entriesread, out int totalentries, out int resume_handle);

[DllImport(
" Netapi32.dll " )]
extern static int NetApiBufferFree(IntPtr Buffer);

[StructLayout(LayoutKind.Sequential, CharSet
= CharSet.Unicode)]
public struct LOCALGROUP_USERS_INFO_0
{
public string groupname;
}

[DllImport(
" Netapi32.dll " )]
public extern static int NetUserGetLocalGroups([MarshalAs(UnmanagedType.LPWStr)] string servername, [MarshalAs(UnmanagedType.LPWStr)] string username, int level, int flags, out IntPtr bufptr, int prefmaxlen, out int entriesread, out int totalentries);

[StructLayout(LayoutKind.Sequential, CharSet
= CharSet.Unicode)]
public struct USER_INFO_1
{
public string usri1_name;
public string usri1_password;
public int usri1_password_age;
public int usri1_priv;
public string usri1_home_dir;
public string comment;
public int usri1_flags;
public string usri1_script_path;
}

[StructLayout(LayoutKind.Sequential, CharSet
= CharSet.Unicode)]
public struct LOCALGROUP_INFO_1
{
public string grpi1_name;
public string grpi1_comment;
}

/// <summary>
/// 添加一个用户,添加失败后返回非0 。
/// </summary>
/// <param name="serverName"> 机器名称,如果是本机,请设置为null </param>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <param name="strComment"></param>
public void AddUser( string serverName, string userName, string password, string strComment)
{
USER_INFO_1 NewUser
= new USER_INFO_1(); // 创建一个USER_INFO_1实例

NewUser.usri1_name
= userName; // Allocates the username
NewUser.usri1_password = password; // allocates the password
NewUser.usri1_priv = 1 ; // Sets the account type to USER_PRIV_USER
NewUser.usri1_home_dir = null ; // We didn't supply a Home Directory
NewUser.comment = strComment; // Comment on the User
NewUser.usri1_script_path = null ; // We didn't supply a Logon Script Path

if (NetUserAdd(serverName, 1 , ref NewUser, 0 ) != 0 ) // 添加失败后返回非0
{
MessageBox.Show(
" Error Adding User " , " Error " , MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

/// <summary>
/// 添加一个用户,添加失败后返回非0 。
/// </summary>
/// <param name="serverName"> 机器名称,如果是本机,请设置为null </param>
/// <param name="groupName"></param>
/// <param name="strComment"></param>
public void AddGroup( string serverName, string groupName, string strComment)
{
LOCALGROUP_INFO_1 NewGroup
= new LOCALGROUP_INFO_1();

NewGroup.grpi1_name
= groupName;
NewGroup.grpi1_comment
= strComment;
if (NetLocalGroupAdd(serverName, 1 , ref NewGroup, 0 ) != 0 ) // 添加失败后返回非0
{
MessageBox.Show(
" Error Adding Group " , " Error " , MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

/// <summary>
/// 在本地组中添加一个用户成员,添加失败后返回非0 。
/// </summary>
/// <param name="serverName"> 机器名称,如果是本机,请设置为null </param>
/// <param name="groupName"></param>
/// <param name="strComment"></param>
public void GroupAddMembers( string serverName, string groupName, string userName)
{
LOCALGROUP_MEMBERS_INFO_3 NewMember
= new LOCALGROUP_MEMBERS_INFO_3();
NewMember.domainandname
= userName;
if (NetLocalGroupAddMembers(serverName, groupName, 3 , ref NewMember, 1 ) != 0 ) // 添加失败后返回非0
{
MessageBox.Show(
" Error Adding Group Member " , " Error " , MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}


/// <summary>
/// 删除一个用户,同时将删除这个用户在任何组中的关系,删除失败后返回非0。
/// </summary>
/// <param name="serverName"> 机器名称,如果是本机,请设置为null </param>
/// <param name="userName"></param>
public void RemoveUser( string serverName, string userName)
{
if (NetUserDel(serverName, userName) != 0 ) // 删除失败后返回非0
{
MessageBox.Show(
" Error Removing User " , " Error " , MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

/// <summary>
/// 获取一个用户的信息,失败后返回非0。
/// </summary>
/// <param name="serverName"> 机器名称,如果是本机,请设置为null </param>
/// <param name="userName"></param>
public void GetUserInfo( string serverName, string userName)
{
IntPtr bufPtr;
USER_INFO_1 User
= new USER_INFO_1();
if (NetUserGetInfo(serverName, userName, 1 , out bufPtr) != 0 )
{
MessageBox.Show(
" Error Getting User Info " , " Error " , MessageBoxButtons.OK, MessageBoxIcon.Error);
}
User
= (USER_INFO_1)Marshal.PtrToStructure(bufPtr, typeof (USER_INFO_1));
MessageBox.Show(
" Users Name: " + User.usri1_name + " \nUsers Comments: " + User.comment + " \nUsers Privilege Level: " + User.usri1_priv + " \nUsers flags: " + User.usri1_flags + " \nUsers home dir: " + User.usri1_home_dir);
}

/// <summary>
/// 修改一个用户,失败后返回非0。这儿我只做了简的测试,如果要修改用户更多的信息,请加上其它信息。
/// </summary>
/// <param name="serverName"> 机器名称,如果是本机,请设置为null </param>
/// <param name="userName"></param>
public void ModifyUser( string serverName, string userName)
{
USER_INFO_1 Update
= new USER_INFO_1();
Update.comment
= " This is Our C# Updated Comment " ;
// Update.usri1_priv = 2; // Note that this can only be obtained programmatically using NetUserGetInfo
if (NetUserSetInfo(serverName, userName, 1 , ref Update, 0 ) != 0 )
{
MessageBox.Show(
" Error Setting User Info " , " Error " , MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

/// <summary>
/// 修改一个用户的密码,失败后返回非0。
/// </summary>
/// <param name="serverName"> 机器名称,如果是本机,请设置为null </param>
/// <param name="userName"></param>
public void ModifyUserPassword( string serverName, string userName, string oldPassword, string newPassword)
{
if (NetUserChangePassword(serverName, userName, oldPassword, newPassword) != 0 )
{
MessageBox.Show(
" Error Changing User Password " , " Error " , MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

/// <summary>
/// 获取机器上所有的用户信息。
/// </summary>
/// <param name="serverName"> 机器名称,如果是本机,请设置为null </param>
public void GetAllUserInfo( string serverName)
{
int EntriesRead;
int TotalEntries;
int Resume;
IntPtr bufPtr;

NetUserEnum(serverName,
0 , 2 , out bufPtr, - 1 , out EntriesRead, out TotalEntries, out Resume);
if (EntriesRead > 0 )
{
USER_INFO_0[] Users
= new USER_INFO_0[EntriesRead];
IntPtr iter
= bufPtr;
for ( int i = 0 ; i < EntriesRead; i ++ )
{
Users[i]
= (USER_INFO_0)Marshal.PtrToStructure(iter, typeof (USER_INFO_0));
iter
= (IntPtr)(( int )iter + Marshal.SizeOf( typeof (USER_INFO_0)));
MessageBox.Show(Users[i].Username);
}
NetApiBufferFree(bufPtr);
}
}

/// <summary>
/// 获取机器上某用户所属于的本地组信息。
/// </summary>
/// <param name="serverName"> 机器名称,如果是本机,请设置为null </param>
/// <param name="userName"></param>
public void UserInLocalGroups( string serverName, string userName)
{
int EntriesRead;
int TotalEntries;
IntPtr bufPtr;

NetUserGetLocalGroups(serverName, userName,
0 , 0 , out bufPtr, 1024 , out EntriesRead, out TotalEntries);

if (EntriesRead > 0 )
{
LOCALGROUP_USERS_INFO_0[] RetGroups
= new LOCALGROUP_USERS_INFO_0[EntriesRead];
IntPtr iter
= bufPtr;
for ( int i = 0 ; i < EntriesRead; i ++ )
{
RetGroups[i]
= (LOCALGROUP_USERS_INFO_0)Marshal.PtrToStructure(iter, typeof (LOCALGROUP_USERS_INFO_0));
iter
= (IntPtr)(( int )iter + Marshal.SizeOf( typeof (LOCALGROUP_USERS_INFO_0)));
MessageBox.Show(RetGroups[i].groupname);
}
NetApiBufferFree(bufPtr);
}
}
}
}

 

转载于:https://www.cnblogs.com/kevinxiong/archive/2010/02/27/1674902.html

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值