使用NetUserAdd编程创建远程用户

本文介绍了一种使用NetUserAdd函数创建远程Windows用户的方法。当当前登录用户不具备远程机器的管理员权限时,通常此操作会失败。文章通过建立网络连接绕过权限限制,实现了在远程服务器上创建新用户。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()就可以搞定。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值