使用NetUserAdd API函数创建远程用户

时间:2023-01-16 07:24:36

http://apps.hi.baidu.com/share/detail/33407620

使用NetUserAdd编程创建远程用户
Windows API NetUserAdd()可以创建Windows用户,无论是本地还是远程的用户。

NET_API_STATUS NetUserAdd(
LMSTR servername,
DWORD level,
LPBYTE buf,
LPDWORD parm_err
);

servername
[in] Pointer to a constant string that specifies the DNS or NetBIOS name of the remote server on which the function is to execute. If this parameter is NULL, the local computer is used.

尽管MSDN如是说,但是有一个问题:如果当前的登录用户在远程机器上没有管理员的权限,创建远程用户会失败。例如:当前用户是主机A上的用户Administrator,希望能够创建主机B上一个新用户testB,显然用户HostA\Administrator并不是主机B上的Administrators组的用户,所以创建会因安全问题失败。我们必须提供Windows主机B上的具有管理员权限的用户名和口令,如HostB\Administrator,但即使如此NetUserAdd()该怎样告诉Windows呢?

我想过Impersonate等函数,但比如ImpersonateLogonUser()并不能模拟远程用户。在国外的网站上也找不到类似的例子,正在一筹莫展之时,突然想到了试试先让主机A与主机B建立一个网络连接,即调用WNetAddConnection2()建立一个网络映射,然后再调用NetUserAdd(),结果居然成功了!

代码如下:

NETRESOURCE nr;

memset(&nr,0,sizeof(nr));
   nr.dwType = RESOURCETYPE_DISK;
   nr.lpLocalName = "X:";
   nr.lpRemoteName = "\\\\sean01\\d$\\test";

DWORD dwRet = WNetAddConnection2(&nr,"password","sean01\\administrator",CONNECT_UPDATE_PROFILE);

USER_INFO_1 NewUser;

memset(&NewUser,0,sizeof(NewUser));

NewUser.usri1_name = L"UserTestOne"; // Allocates the username
   NewUser.usri1_password = L"abcd1234"; // 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.usri1_comment = L"Create remote user"; // Comment on the User
   NewUser.usri1_script_path = NULL; // We didn't supply a Logon Script Path

dwRet = NetUserAdd(L"\\\\sean01" ,1 ,(LPBYTE)&NewUser, 0);
   if ( dwRet != 0 ) // If the call fails we get a non-zero value
   {
     MessageBox(NULL,"Error Adding User",NULL,NULL);
   }
   else
     MessageBox(NULL,"CreateUser ok",NULL,NULL);

尽管不是最好的办法,但可以使用。希望哪天可以知道怎样用NetUserAdd()就可以搞定。

http://www.cnblogs.com/-clq/archive/2012/02/23/2364559.html