zhiye_wang

向星空仰望的越深,越发现自己的渺小

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  31 随笔 :: 1 文章 :: 2 评论 :: 0 Trackbacks
 1/* 
 2 * =====================================================================================
 3 *       Filename:  userGroup.h 
 4 * =====================================================================================
 5 */

 6 
 7#ifndef USER_GROUP_H
 8#define USER_GROUP_H
 9#pragma once
10#include <windows.h>
11#include <stdio.h>
12#include <tchar.h>
13#include <string>
14using namespace std;
15#include <Aclapi.h>
16#pragma comment(lib,"Advapi32.lib")
17#include <LM.h>
18#pragma comment(lib,"Netapi32.lib")
19#include <Winnetwk.h>
20#pragma comment(lib,"Mpr.lib")
21#include <Wtsapi32.h>
22#pragma comment(lib,"Wtsapi32.lib")
23typedef enum
24{
25    e_CREATE_SUCCESS,
26    e_CREATE_FAILED,
27    e_CREATE_STOP,
28    e_CREATE_USER_EXIST,
29    e_CREATE_PasswordTooShort,
30    e_CREATE_ACCESS_DENIED,
31    e_CREATE_BAD_NETPATH,
32    e_CREATE_INVALID_LEVEL,
33    e_CREATE_InvalidComputer,
34    e_CREATE_NotPrimary,
35    e_CREATE_GroupExists,
36}
CREATE_RETURN_RES;
37CREATE_RETURN_RES createNewUser(LPTSTR lpServerName,LPTSTR lpUserName, LPTSTR lpUserPwd);
38#
  1/* 
  2 * =====================================================================================
  3 *       Filename:  userGroup.cpp 
  4 * =====================================================================================
  5 */

  6 
  7#include "stdafx.h"
  8#include "userGroup.h"
  9#include <intsafe.h>
 10BOOL TakeOwnshipOfDiretory(wchar_t *pwDir,wchar_t *pwUserName,wchar_t *pwServerName)
 11{
 12    USER_INFO_4 *pUserInfo4 = NULL;
 13    DWORD nStatus;
 14    BOOL bRet = FALSE;
 15    PSID pSIDAdmin = NULL;
 16    SID_IDENTIFIER_AUTHORITY SIDAuthNT = SECURITY_NT_AUTHORITY;
 17    EXPLICIT_ACCESS ea[2= {0};
 18    PACL pACL = NULL;
 19    PSECURITY_DESCRIPTOR pSD = NULL;
 20    do 
 21    {
 22        nStatus = NetUserGetInfo(pwServerName, pwUserName, 4, (LPBYTE *)&pUserInfo4);
 23        if(NERR_Success != nStatus)
 24        {
 25            printf("NetUserGetInfo failed\n");
 26            break;
 27        }

 28        nStatus = GetNamedSecurityInfoW(pwDir, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION, NULL, NULL, NULL, NULL, &pSD);
 29        if(NERR_Success != nStatus)
 30        {
 31            printf("GetNamedSecurityInfo Failed\n"); 
 32            break;
 33        }

 34        if(FALSE == SetSecurityDescriptorControl(pSD, SE_DACL_PROTECTED, SE_DACL_PROTECTED))
 35        {
 36            printf("SetSecurityDescriptorControl failed\n");
 37            break;
 38        }

 39        if(FALSE == SetFileSecurityW(pwDir, DACL_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION, pSD))
 40        {
 41            printf("SetFileSecurity failed\n");
 42            break;
 43        }

 44        if(FALSE == AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 000000&pSIDAdmin))
 45        {
 46            printf("AllocataAndInitializeSid failed\n");
 47            break;
 48        }

 49        ea[0].grfAccessPermissions = SPECIFIC_RIGHTS_ALL|STANDARD_RIGHTS_ALL;
 50        ea[0].grfAccessMode = GRANT_ACCESS;
 51        ea[0].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
 52        ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
 53        ea[0].Trustee.TrusteeType = TRUSTEE_IS_USER;
 54        ea[0].Trustee.ptstrName = (LPTSTR)pUserInfo4->usri4_user_sid;
 55        // Set full control for Administrators.
 56        ea[1].grfAccessPermissions = SPECIFIC_RIGHTS_ALL|STANDARD_RIGHTS_ALL;
 57        ea[1].grfAccessMode = GRANT_ACCESS;
 58        ea[1].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
 59        ea[1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
 60        ea[1].Trustee.TrusteeType = TRUSTEE_IS_GROUP;
 61        ea[1].Trustee.ptstrName = (LPTSTR)pSIDAdmin;
 62        if(NERR_Success != SetEntriesInAcl(2, ea, NULL, &pACL))
 63        {
 64            printf("set entriesInAcl failed\n");
 65            break;
 66        }

 67        if(NERR_Success != SetNamedSecurityInfoW(pwDir,SE_FILE_OBJECT,DACL_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION, NULL, pSIDAdmin,pACL,NULL))
 68        {
 69            printf("SetNamedSecurityInfo FAILED\n");
 70            break;
 71        }

 72        bRet =TRUE;
 73    }
 while (0);
 74    if(NULL != pUserInfo4)
 75    {
 76        NetApiBufferFree(pUserInfo4);
 77    }

 78    if(NULL != pSD)
 79    {
 80        LocalFree(pSD);
 81    }

 82    if(NULL == pSIDAdmin)
 83    {
 84        FreeSid(pSIDAdmin);
 85    }

 86    if(NULL != pACL)
 87    {
 88        LocalFree(pACL);
 89    }

 90    return bRet;
 91}

 92 
 93// lpServerName 是带双斜杠的域名
 94BOOL SetUserToUserGroup(LPTSTR lpServerName,LPTSTR lpUserName)
 95{
 96    NET_API_STATUS netStatus;
 97    BOOL bOK = FALSE;
 98    do 
 99    {
100        LOCALGROUP_MEMBERS_INFO_3 LGMInfo;
101        LGMInfo.lgrmi3_domainandname = lpUserName;
102        netStatus = NetLocalGroupAddMembers(lpServerName, _T("Users"), 3,(LPBYTE)&LGMInfo, 1);
103        if (NERR_Success != netStatus && ERROR_MEMBER_IN_ALIAS != netStatus)
104        {
105            TCHAR chErr[32= {0};
106            wsprintf(chErr,_T("%susers%s,%d"),_T("加入"), _T("失败"),GetLastError());
107            MessageBox(NULL,chErr,_T("错误"),MB_OK|MB_ICONERROR);
108            break;
109        }

110        netStatus = NetLocalGroupAddMembers(lpServerName,_T("Remote Desktop Users"), 3, (LPBYTE)&LGMInfo, 1);
111        if (NERR_Success != netStatus && ERROR_MEMBER_IN_ALIAS != netStatus)
112        {
113            TCHAR chErr[32= {0};
114            wsprintf(chErr,_T("%susers%s,%d"),_T("加入"), _T("失败"),GetLastError());
115            MessageBox(NULL,chErr,_T("错误"),MB_OK|MB_ICONERROR);
116            break;
117        }

118        
119        netStatus = NetLocalGroupAddMembers(NULL,L"Remote Desktop Users",3,(LPBYTE)&LGMInfo,1);
120        if (NERR_Success != netStatus && ERROR_MEMBER_IN_ALIAS != netStatus)
121        {
122            TCHAR chErr[32= {0};
123            wsprintf(chErr,_T("%susers%s,%d"),_T("加入"), _T("失败"),GetLastError());
124            MessageBox(NULL,chErr,_T("错误"),MB_OK|MB_ICONERROR);
125            break;
126        }

127        bOK = TRUE;
128    }
 while (0);
129    return bOK;
130}

131BOOL IsDomainUser()
132{
133    TCHAR *pDomainName = NULL;
134    DWORD dwDomainNameSize = 0;
135    TCHAR compName[128= {0};
136    DWORD dwCompNameLen = 128;
137    do 
138    {
139        //Minimum supported client: Windows Vista 
140        //Minimum supported server: Windows Server 2003 
141        BOOL bRes = WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE,WTS_CURRENT_SESSION,WTSDomainName,&pDomainName,&dwDomainNameSize);
142        if (bRes == FALSE)
143        {
144            return FALSE;
145        }

146        GetComputerName(compName, &dwCompNameLen);
147        int ret = lstrcmpi(pDomainName,compName);
148        WTSFreeMemory(pDomainName);
149        if (0 != ret)
150        {
151            return TRUE; // 域名 != 计算机名, 在域中
152        }

153        
154    }
 while (0);
155        
156    return FALSE; // 域名 == 计算机名, 不在域中
157}

158 
159 /* 
160 * =====================================================================================
161 *           Filename:  userGroup.cpp 
162 *        Description:  add user 
163 *            Created:  2014年11月22日15:27:18
164 *             Author:  wzy
165 *
166 *       lpServerName:  传入参数, 域名, 不带双反斜杠
167 *         lpUserName:  传入参数, 用户, 以杠零结束的字符串
168 *          lpUserPwd:  传入参数, 密码, 以杠零结束的字符串
169 *                other:  
170 * =====================================================================================
171 */
 
172CREATE_RETURN_RES createNewUser(LPTSTR lpServerName, LPTSTR lpUserName, LPTSTR lpUserPwd)
173{
174    USER_INFO_4 ui      = {0};
175    DWORD dwLevel       = 4;
176    DWORD dwError       = 0;
177    LPBYTE lpBuf        = NULL;
178    LPTSTR pwServerName = NULL;
179    NET_API_STATUS      nStatus;
180    
181    CREATE_RETURN_RES cRes = e_CREATE_FAILED;
182    
183    do 
184    {
185        
186        if (NULL == lpUserName)
187        {
188            break ;
189        }

190        DWORD dwLen = _tcslen(lpServerName);
191        
192        
193        TCHAR buffer[256= {0};
194        DWORD dwSize = sizeof(buffer);
195        GetComputerNameEx(ComputerNameDnsDomain, buffer, &dwSize);// buffer本机所属域名
196        
197        CString str;
198        str.SetString(buffer);
199        
200        TCHAR chServerName[512= _T("\\\\");
201        pwServerName = lstrcat(chServerName, str.GetBuffer());
202        
203        /*
204        TCHAR chServerName[512] = _T("\\\\");
205        pwServerName = lstrcat(chServerName, (LPCWSTR)lpServerName);
206        */

207        if (0 == _tcscmp(lpServerName, _T("")) || (NULL == lpServerName))
208        {
209            pwServerName = NULL;
210        }

211        
212        //if (0 == IsDomainUser()) // 本地计算机名 == 本机所属域名
213        //{
214        //    pwServerName = NULL;
215        //}
216        ui.usri4_name = lpUserName;
217        ui.usri4_password = lpUserPwd;
218        ui.usri4_priv = USER_PRIV_USER;
219        ui.usri4_home_dir = NULL;
220        ui.usri4_comment = NULL;
221        ui.usri4_full_name = lpUserName;
222        ui.usri4_flags = UF_SCRIPT;
223        ui.usri4_profile = NULL;
224        
225        nStatus = NetUserGetInfo(pwServerName, ui.usri4_name, 4, (LPBYTE *)&lpBuf);
226        DWORD asdf = nStatus;
227        
228        if (ERROR_ACCESS_DENIED == nStatus)
229        {
230            MessageBox(NULL,_T("访问拒绝"),_T("错误"),MB_OK|MB_ICONERROR);
231            cRes = e_CREATE_ACCESS_DENIED;
232            break ;
233        }

234        else if (ERROR_BAD_NETPATH == nStatus)
235        {
236            MessageBox(NULL,_T("网络路径不可用"),_T("错误"),MB_OK|MB_ICONERROR);
237            cRes = e_CREATE_BAD_NETPATH;
238            break ;
239        }

240        else if (ERROR_INVALID_LEVEL == nStatus)
241        {
242            MessageBox(NULL,_T("无效的级别"),_T("错误"),MB_OK|MB_ICONERROR);
243            cRes = e_CREATE_INVALID_LEVEL;           
244            break ;
245        }

246        else if (NERR_InvalidComputer == nStatus)
247        {
248            MessageBox(NULL,_T("无效的电脑"),_T("错误"),MB_OK|MB_ICONERROR);
249            cRes = e_CREATE_InvalidComputer;
250            break ;
251        }

252        else if (NERR_Success == nStatus) // 已存在
253        {
254            
255            MessageBox(NULL,_T("用户名已存在,请重新输入用户名"),_T("错误"),MB_OK|MB_ICONERROR);
256            cRes = e_CREATE_USER_EXIST;
257            break ;
258        }

259        else if (NERR_UserNotFound == nStatus) // 不存在,创建 
260        {
261           // ui.usri4_primary_group_id = DOMAIN_GROUP_RID_USERS;
262            ui.usri4_flags = UF_DONT_EXPIRE_PASSWD;
263            ui.usri4_acct_expires = TIMEQ_FOREVER;
264            ui.usri4_priv = USER_PRIV_USER;
265            ui.usri4_logon_hours = NULL;    
266            ui.usri4_script_path = NULL;
267            
268            nStatus = NetUserAdd(pwServerName, dwLevel, (LPBYTE)&ui, &dwError);
269            TakeOwnshipOfDiretory(ui.usri4_home_dir, ui.usri4_name, pwServerName);
270            
271            if (NERR_Success != nStatus) // 创建失败
272            {
273                
274                if(NERR_PasswordTooShort == nStatus)
275                {
276                    MessageBox(NULL,_T("PasswordTooShort"),_T("错误"),MB_OK|MB_ICONERROR);
277                    cRes = e_CREATE_PasswordTooShort;
278                    break ;
279                }

280                else if (NERR_UserExists == nStatus)
281                {
282                    MessageBox(NULL,_T("UserExists"),_T("错误"),MB_OK|MB_ICONERROR);
283                    cRes = e_CREATE_USER_EXIST;
284                    break ;
285                }

286                
287                else if(NERR_GroupExists == nStatus)
288                {
289                    MessageBox(NULL,_T("GroupExists"),_T("错误"),MB_OK|MB_ICONERROR);
290                    cRes = e_CREATE_GroupExists;
291                }

292                else if (NERR_NotPrimary == nStatus)
293                {
294                    MessageBox(NULL,_T("NotPrimary"),_T("错误"),MB_OK|MB_ICONERROR);
295                    cRes = e_CREATE_NotPrimary;
296                    break ;
297                }

298                else if (NERR_InvalidComputer == nStatus)
299                {
300                    MessageBox(NULL,_T("InvalidComputer"),_T("错误"),MB_OK|MB_ICONERROR);
301                    cRes = e_CREATE_InvalidComputer;
302                    break ;
303                }

304                else if (ERROR_ACCESS_DENIED == nStatus)
305                {
306                    MessageBox(NULL,_T("ACCESS_DENIED"),_T("错误"),MB_OK|MB_ICONERROR);
307                    cRes = e_CREATE_ACCESS_DENIED;
308                    break ;
309                }

310                else
311                {
312                    MessageBox(NULL,_T("创建用户失败"),_T("错误"),MB_OK|MB_ICONERROR);
313                    cRes = e_CREATE_FAILED;
314                    break ;
315                }

316            }
 // endif
317            else if (NERR_Success == nStatus)// 创建成功,移入User和Remote Desktop Users组
318            {
319                 cRes = e_CREATE_SUCCESS;
320                 
321                 if (!SetUserToUserGroup(pwServerName, ui.usri4_name))
322                 {
323                     ui.usri4_flags |= UF_DONT_EXPIRE_PASSWD;
324                     break;
325                 }

326            }

327            
328        }

329        else
330        {
331            break ;
332        }

333        
334    }
 while (0);
335    
336    if (NULL != ui.usri4_name)
337    {
338        ui.usri4_name = NULL;
339    }

340    if (NULL != ui.usri4_password)
341    {
342        ui.usri4_password = NULL;
343    }
 
344    if (NULL != ui.usri4_home_dir)
345    {
346        ui.usri4_home_dir = NULL;
347    }

348    if(NULL != ui.usri4_comment)
349    {
350        ui.usri4_comment = NULL;
351    }

352    if (NULL != ui.usri4_full_name)
353    {
354        ui.usri4_full_name = NULL;
355    }

356    if (NULL != ui.usri4_profile)
357    {
358        ui.usri4_profile = NULL;
359    }

360    if (NULL != ui.usri4_script_path)
361    {
362        ui.usri4_script_path = NULL;
363    }

364    
365    return cRes;
366}
endif
 //USER_GROUP_H

UserGroup.cpp

asdfa



posted on 2014-12-23 17:47 zhiye_wang 阅读(437) 评论(0)  编辑 收藏 引用 所属分类: windows

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理