声明:未经允许不得转载,转载时请标注来源;禁止用作商业及其他衍生目的。
有误请指正,侵权请联系删除。有更好的方法也请联系我求赞,关注,评论
主要目的:实现枚举本地的所有用户。
食材:netapi32.dll
[void](Add-Type -TypeDefinition @"
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
public class UserEnum
{
// 定义Netapi32.dll库中的函数
[DllImport("Netapi32.dll", CharSet = CharSet.Unicode)]
private static extern int NetUserEnum(
string serverName,
int level,
int filter,
out IntPtr userInfo,
int prefMaxLen,
out int entriesRead,
out int totalEntries,
out int resumeHandle);
[DllImport("Netapi32.dll")]
private static extern int NetApiBufferFree(IntPtr buffer);
// 定义USER_INFO_1结构体
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct USER_INFO_1
{
public string username;
public string password;
public int passwordAge;
public int privilege;
public string homeDirectory;
public string comment;
public int flags;
public string scriptPath;
}
public static List<string> EnumerateUsers()
{
// 调用NetUserEnum来获取用户信息
List<string> userList = new List<string>();
int entriesRead, totalEntries, resumeHandle;
IntPtr pBuffer;
int result = NetUserEnum(null, 1, 0, out pBuffer, -1, out entriesRead, out totalEntries, out resumeHandle);
if (result == 0 && entriesRead > 0)
{
IntPtr pBufferTemp = pBuffer;
for (int i = 0; i < entriesRead; i++)
{
// 将指针转换为USER_INFO_1结构体
USER_INFO_1 user = (USER_INFO_1)Marshal.PtrToStructure(pBufferTemp, typeof(USER_INFO_1));
userList.Add(user.username);
// 将指针移到下一个结构体
pBufferTemp = new IntPtr(pBufferTemp.ToInt64() + Marshal.SizeOf(typeof(USER_INFO_1)));
}
// 释放内存
NetApiBufferFree(pBuffer);
}
return userList;
}
}
"@)
[UserEnum]::EnumerateUsers() #实现本地用户列表的枚举
优点:可枚举net.exe无法枚举的内容
缺点:c#模块过大,主要部分(API,结构)过于复杂,但都可以简化(为效率和稳定性应适当减少重复循环性质的powershell代码)