简介
windows 下添加用户的API:
NetUserAdd // 添加用户
NetLocalGroupAddMembers // 为用户添加用户组
api需要unicode环境,成功执行需要用户管理员权限
代码
#include <Windows.h>
#include <lmaccess.h>
#include <lm.h>
#pragma comment(lib, "netapi32.lib")
NET_API_STATUS AddUser(PTCHAR name, PTCHAR passwd)
{
USER_INFO_1 ui;
DWORD dwLevel = 1;
DWORD dwError = 0;
NET_API_STATUS nStatus;
LOCALGROUP_MEMBERS_INFO_3 memberInfo;
ui.usri1_name = name;
ui.usri1_password = passwd;
ui.usri1_priv = USER_PRIV_USER;
ui.usri1_home_dir = NULL;
ui.usri1_comment = NULL;
ui.usri1_flags = UF_SCRIPT;
ui.usri1_script_path = NULL;
// 添加用户需要管理员权限,0是成功,5是权限不足,2224是用户已存在
nStatus = NetUserAdd(NULL,
dwLevel,
(LPBYTE)&ui,
&dwError);
memberInfo.lgrmi3_domainandname = name;
// 将用户添加到管理员组
NetLocalGroupAddMembers(NULL, L"Administrators", 3, (LPBYTE)&memberInfo, 1);
return nStatus;
}
int wmain(int argc, wchar_t* argv[]) {
TCHAR user[] = TEXT("admin$");
TCHAR pass[] = TEXT("1");
NET_API_STATUS nStatus;
nStatus = AddUser(user, pass);
printf("A system error has occurred: %d\n", nStatus);
}