forked from laochiangx/Common.Utility
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathADHelp.cs
1374 lines (1241 loc) · 45.9 KB
/
ADHelp.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using System.Security.Principal;
using System.Runtime.InteropServices;
//Download by http://www.codefans.net
namespace UserDLL
{
sealed class ADHelper
{
#region 私有变量
/// <summary>
/// homeMTA
/// </summary>
private static string homeMTA = ""; //请填写自己的环境变量
/// <summary>
/// homeMDB
/// </summary>
private static string homeMDB = ""; //请填写自己的环境变量
/// <summary>
/// msExchHomeServerName
/// </summary>
private static string msExchHomeServerName = ""; //请填写自己的环境变量
///<summary>
/// 域名
///</summary>
//private static string DomainName = "td-tech.net"; //实际
private static string DomainName = "contoso.com"; //测试用
/// <summary>
/// LDAP 地址
/// </summary>
private static string LDAPDomain = "DC=net,DC=TD-TECH";
/// <summary>
/// LDAP绑定路径
/// </summary>
private static string ADPath = "LDAP://Contoso.com"; //测试用
private static string sPrincpleNameTail = "@cinf.com";
/// <summary>
/// 登录帐号
/// </summary>
private static string ADUser = @"contoso\oa";
/// <summary>
/// 登录密码
/// </summary>
//private static string ADPassword = "3edc5tgB"; //实际
private static string ADPassword = "1qaz2wsX"; //测试用
#endregion
#region 枚举常量
/// <summary>
/// 用户登录验证结果
/// </summary>
public enum LoginResult
{
///
/// 正常登录
///
LOGIN_USER_OK = 0,
///
/// 用户不存在
///
LOGIN_USER_DOESNT_EXIST,
///
/// 用户帐号被禁用
///
LOGIN_USER_ACCOUNT_INACTIVE,
///
/// 用户密码不正确
///
LOGIN_USER_PASSWORD_INCORRECT
}
/// <summary>
/// 用户属性定义标志
/// </summary>
public enum ADS_USER_FLAG_ENUM
{
///
/// 登录脚本标志。如果通过 ADSI LDAP 进行读或写操作时,
/// 该标志失效。如果通过 ADSI WINNT,该标志为只读。
///
ADS_UF_SCRIPT = 0X0001,
///
/// 用户帐号禁用标志
///
ADS_UF_ACCOUNTDISABLE = 0X0002,
///
/// 主文件夹标志
///
ADS_UF_HOMEDIR_REQUIRED = 0X0008,
///
/// 过期标志
///
ADS_UF_LOCKOUT = 0X0010,
///
/// 用户密码不是必须的
///
ADS_UF_PASSWD_NOTREQD = 0X0020,
///
/// 密码不能更改标志
///
ADS_UF_PASSWD_CANT_CHANGE = 0X0040,
///
/// 使用可逆的加密保存密码
///
ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0X0080,
///
/// 本地帐号标志
///
ADS_UF_TEMP_DUPLICATE_ACCOUNT = 0X0100,
///
/// 普通用户的默认帐号类型
///
ADS_UF_NORMAL_ACCOUNT = 0X0200,
///
/// 跨域的信任帐号标志
///
ADS_UF_INTERDOMAIN_TRUST_ACCOUNT = 0X0800,
///
/// 工作站信任帐号标志
///
ADS_UF_WORKSTATION_TRUST_ACCOUNT = 0x1000,
///
/// 服务器信任帐号标志
///
ADS_UF_SERVER_TRUST_ACCOUNT = 0X2000,
///
/// 密码永不过期标志
///
ADS_UF_DONT_EXPIRE_PASSWD = 0X10000,
///
/// MNS 帐号标志
///
ADS_UF_MNS_LOGON_ACCOUNT = 0X20000,
///
/// 交互式登录必须使用智能卡
///
ADS_UF_SMARTCARD_REQUIRED = 0X40000,
///
/// 当设置该标志时,服务帐号(用户或计算机帐号)将通过 Kerberos 委托信任
///
ADS_UF_TRUSTED_FOR_DELEGATION = 0X80000,
///
/// 当设置该标志时,即使服务帐号是通过 Kerberos 委托信任的,敏感帐号不能被委托
///
ADS_UF_NOT_DELEGATED = 0X100000,
///
/// 此帐号需要 DES 加密类型
///
ADS_UF_USE_DES_KEY_ONLY = 0X200000,
///
/// 不要进行 Kerberos 预身份验证
///
ADS_UF_DONT_REQUIRE_PREAUTH = 0X4000000,
///
/// 用户密码过期标志
///
ADS_UF_PASSWORD_EXPIRED = 0X800000,
///
/// 用户帐号可委托标志
///
ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0X1000000
}
#endregion
#region 构造函数
public ADHelper()
{
//
// System.Environment.UserName
}
/// <summary>
/// 多联的AD构造函数
/// </summary>
/// <param name="sADPath"></param>
/// <param name="sDomainName"></param>
/// <param name="sADUser"></param>
/// <param name="sADUserPWD"></param>
public ADHelper(string sADPath, string sDomainName, string sADUser, string sADUserPWD)
{
ADPath = sADPath;
DomainName = sDomainName;
ADUser = sADUser;
ADPassword = sADUserPWD;
}
#endregion
#region GetDirectoryObject
/// <summary>
/// 获得DirectoryEntry对象实例,以管理员登陆AD
/// </summary>
/// <returns></returns>
private static DirectoryEntry GetDirectoryObject()
{
DirectoryEntry entry = new DirectoryEntry(ADPath, ADUser, ADPassword, AuthenticationTypes.Secure);
return entry;
}
/// <summary>
/// 根据指定用户名和密码获得相应DirectoryEntry实体
/// </summary>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <returns></returns>
private static DirectoryEntry GetDirectoryObject(string userName, string password)
{
DirectoryEntry entry = new DirectoryEntry(ADPath,
userName, password, AuthenticationTypes.None);
return entry;
}
/// <summary>
/// i.e. /CN=Users,DC=creditsights, DC=cyberelves, DC=Com
/// </summary>
/// <param name="domainReference"></param>
/// <returns></returns>
private static DirectoryEntry GetDirectoryObject(string domainReference)
{
DirectoryEntry entry = new DirectoryEntry(ADPath + domainReference, ADUser, ADPassword,
AuthenticationTypes.Secure);
return entry;
}
/// <summary>
/// 获得以UserName,Password创建的DirectoryEntry
/// </summary>
/// <param name="domainReference"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <returns></returns>
private static DirectoryEntry GetDirectoryObject(string domainReference,
string userName, string password)
{
DirectoryEntry entry = new DirectoryEntry(ADPath + domainReference,
userName, password, AuthenticationTypes.Secure);
return entry;
}
#endregion
#region GetDirectoryEntry
/// <summary>
/// 根据用户公共名称取得用户的 对象
/// </summary>
/// <param name="commonName">用户公共名称</param>
/// <returns>如果找到该用户,则返回用户的 对象;否则返回 null</returns>
public static DirectoryEntry GetDirectoryEntry(string commonName)
{
DirectoryEntry de = GetDirectoryObject();
DirectorySearcher deSearch = new DirectorySearcher(de);
deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";
deSearch.SearchScope = SearchScope.Subtree;
try
{
SearchResult result = deSearch.FindOne();
de = new DirectoryEntry(result.Path);
//de.Username = ADUser;
return de;
}
catch
{
return null;
}
}
/// <summary>
/// 根据用户公共名称和密码取得用户的 对象。
/// </summary>
/// <param name="commonName">用户公共名称</param>
/// <param name="password">用户密码</param>
/// <returns>如果找到该用户,则返回用户的 对象;否则返回 null</returns>
public static DirectoryEntry GetDirectoryEntry(string commonName, string password)
{
DirectoryEntry de = GetDirectoryObject(commonName, password);
DirectorySearcher deSearch = new DirectorySearcher(de);
deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";
deSearch.SearchScope = SearchScope.Subtree;
try
{
SearchResult result = deSearch.FindOne();
de = new DirectoryEntry(result.Path);
return de;
}
catch
{
return null;
}
}
/// <summary>
/// 根据用户帐号称取得用户的 对象
/// </summary>
/// <param name="sAMAccountName">用户帐号名</param>
/// <returns>如果找到该用户,则返回用户的 对象;否则返回 null</returns>
public static DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName)
{
DirectoryEntry de = GetDirectoryObject(ADUser, ADPassword);
DirectorySearcher deSearch = new DirectorySearcher(de);
deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=" + sAMAccountName + "))";
deSearch.SearchScope = SearchScope.Subtree;
try
{
SearchResult result = deSearch.FindOne();
de = new DirectoryEntry(result.Path, ADUser, ADPassword);
return de;
}
catch(Exception ex)
{
return null;
}
}
/// <summary>
/// 根据用户帐号和密码取得用户的 对象
/// </summary>
/// <param name="sAMAccountName">用户帐号名</param>
/// <param name="password">用户密码</param>
/// <returns>如果找到该用户,则返回用户的 对象;否则返回 null</returns>
public static DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName, string password)
{
DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);
if (de != null)
{
string commonName = de.Properties["cn"][0].ToString();
if (GetDirectoryEntry(commonName, password) != null)
return GetDirectoryEntry(commonName, password);
else
return null;
}
else
{
return null;
}
}
/// <summary>
/// 根据组名取得用户组的 对象
/// </summary>
/// <param name="groupName">组名</param>
/// <returns></returns>
public static DirectoryEntry GetDirectoryEntryOfGroup(string groupName)
{
DirectoryEntry de = GetDirectoryObject();
DirectorySearcher deSearch = new DirectorySearcher(de);
deSearch.Filter = "(&(objectClass=group)(cn=" + groupName + "))";
deSearch.SearchScope = SearchScope.Subtree;
try
{
SearchResult result = deSearch.FindOne();
de = new DirectoryEntry(result.Path);
return de;
}
catch
{
return null;
}
}
#endregion
#region GetProperty
/// <summary>
/// 获得指定 指定属性名对应的值
/// </summary>
/// <param name="de">DirectoryEntry对象,如为用户则为用户的对象,部门则为部门的对象</param>
/// <param name="propertyName">属性名称</param>
/// <returns>属性值</returns>
public static string GetProperty(DirectoryEntry de, string propertyName)
{
if (de.Properties.Contains(propertyName))
{
return de.Properties[propertyName][0].ToString();
}
else
{
return string.Empty;
}
}
///
/// 获得指定搜索结果 中指定属性名对应的值
///
///
/// 属性名称
/// 属性值
public static string GetProperty(SearchResult searchResult, string propertyName)
{
if (searchResult.Properties.Contains(propertyName))
{
return searchResult.Properties[propertyName][0].ToString();
}
else
{
return string.Empty;
}
}
/// <summary>
/// 查询制定用户是否是锁定状态
/// </summary>
/// <param name="de"></param>
/// <returns></returns>
public static bool IsAccountLockOut(DirectoryEntry de )
{
return Convert.ToBoolean(de.InvokeGet("IsAccountlocked"));
}
#endregion
#region SetProperty
/// <summary>
/// 设置指定 的属性值
/// </summary>
/// <param name="de"></param>
/// <param name="propertyName">属性名称</param>
/// <param name="propertyValue">属性值</param>
public static void SetProperty(DirectoryEntry de, string propertyName, string propertyValue)
{
if (propertyValue != string.Empty || propertyValue != "" || propertyValue != null)
{
if (de.Properties.Contains(propertyName))
{
de.Properties[propertyName][0] = propertyValue;
}
else
{
de.Properties[propertyName].Add(propertyValue);
}
}
}
#endregion
#region 用户操作
/// <summary>
/// 创建带邮箱的用户
/// </summary>
/// <param name="CommonName">通用名(displayName,系统中显示的中文名字)</param>
/// <param name="Account">帐户名(如ycan)</param>
/// <param name="organizeName">组织单元名(有色院/科技处/信息中心)</param>
/// <param name="password">密码</param>
/// <param name="CreateMail">是否创建邮箱</param>
/// <returns>新建用户的Path 错误则为“”</returns>
public static string CreateADAccount(
string CommonName,//CName
string Account,//EName
string organizeName,//
string password,
bool CreateMail
)
{
//如果Acc存在则返回错误
if (IsAccExists(Account))
return "";
DirectoryEntry entry = null;
DirectoryEntry user = null;
string samAccountName = Account;
try
{
entry = new DirectoryEntry(GetOrganizeNamePath(organizeName), ADUser,
ADPassword, AuthenticationTypes.Secure);
user = entry.Children.Add("CN=" + CommonName, "user");
user.Properties["userPrincipalName"].Value = samAccountName + sPrincpleNameTail;
user.Properties["sAMAccountName"].Add(samAccountName);
user.Properties["displayName"].Add(CommonName);
user.CommitChanges();
user.Invoke("SetPassword", new object[] { password });
//This enables the new user.
user.Properties["userAccountControl"].Value = //0x200; //ADS_UF_NORMAL_ACCOUNT
ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD;
user.CommitChanges();
if (CreateMail)
{
user.Invoke("CreateMailbox", new object[] { homeMDB });
user.CommitChanges();
}
}
catch (Exception e)
{
try
{
user.DeleteTree();
}
catch
{
//return string.Empty;
}
throw e;
}
return user.Path;
}
///// <summary>
///// 启用指定的域账号
///// </summary>
///// <param name="sAMacc">用户的域账号名称</param>
//public static void EnableUser(string sAMacc)
//{
// EnableUser( GetDirectoryEntryByAccount(sAMacc));
//}
/// <summary>
/// 启用指定的域账号
/// </summary>
/// <param name="sAMacc">用户的域账号名称</param>
public static bool EnableUser(string sAMacc)
{
try
{
EnableUser(GetDirectoryEntryByAccount(sAMacc));
return true;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 启用指定帐户
/// </summary>
/// <param name="de"></param>
public static void EnableUser(DirectoryEntry de)
{
de.Properties["userAccountControl"][0] =
ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD;
de.CommitChanges();
de.Close();
}
/// <summary>
/// 禁用指定公共名称的用户
/// </summary>
/// <param name="commonName">用户公共名称</param>
public static void DisableUser(string sAMacc)
{
DisableUser(GetDirectoryEntryByAccount(sAMacc));
}
/// <summary>
/// 禁用指定的帐户
/// </summary>
/// <param name="de"></param>
public static void DisableUser(DirectoryEntry de)
{
//impersonate.BeginImpersonate();
de.Properties["userAccountControl"][0] =
ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNTDISABLE;
de.CommitChanges();
//impersonate.StopImpersonate();
de.Close();
}
/// <summary>
/// 修改用户密码
/// </summary>
/// <param name="commonName">用户公共名称</param>
/// <param name="oldPassword">旧密码</param>
/// <param name="newPassword">新密码</param>
public static void ChangeUserPassword(string commonName, string oldPassword, string newPassword)
{
// to-do: 需要解决密码策略问题
DirectoryEntry oUser = GetDirectoryEntry(commonName);
oUser.Invoke("ChangePassword", new Object[] { oldPassword, newPassword });
oUser.Close();
}
/// <summary>
/// 修改Acc密码
/// </summary>
/// <param name="sAMacc">帐户名称</param>
/// <param name="oldPassword">旧密码</param>
/// <param name="newPassword">新密码</param>
/// <returns>是否成功</returns>
public static bool ChangeAccPassword(string sAMacc, string oldPassword, string newPassword)
{
try
{
if (IsAccExists(sAMacc))
{
// to-do: 需要解决密码策略问题
DirectoryEntry oUser = GetDirectoryEntryByAccount(sAMacc);
//oUser.Invoke("ChangePassword", new Object[] { oldPassword, newPassword });
oUser.Invoke("SetPassword", new object[] { newPassword });
oUser.CommitChanges();
oUser.Close();
return true;
}
else
return false;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 移动用户
/// </summary>
/// <param name="user_path">用户Path</param>
/// <param name="target_path">目标path</param>
/// <returns></returns>
public static string MoveUser(string user_path, string target_path)
{
DirectoryEntry u = new DirectoryEntry(user_path, ADUser, ADPassword);
DirectoryEntry t = new DirectoryEntry(target_path, ADUser, ADPassword);
u.MoveTo(t);
return u.Path;
}
/// <summary>
/// 重名用户
/// </summary>
/// <param name="sAcc"></param>
/// <param name="newDisplayName"></param>
/// <returns></returns>
public static bool RenameUser(string sAcc, string newDisplayName)
{
try
{
if (IsAccExists(sAcc))
{
DirectoryEntry userEntry = GetDirectoryEntryByAccount(sAcc);
//userEntry.Properties["cn"][0] = newDisplayName;
userEntry.Properties["displayName"][0] = newDisplayName;
userEntry.Rename("CN=" + newDisplayName);
userEntry.CommitChanges();
userEntry.Dispose();
return true;
}
else
return false;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 重命名Account
/// </summary>
/// <param name="oldAcc">原Acc</param>
/// <param name="newAcc">新Acc</param>
/// <returns>成功True,如果已经存在新、老Acc则返回false,错误也返回false</returns>
public static bool RenameAcc(string oldAcc, string newAcc)
{
try
{
if (IsAccExists(oldAcc))
{
//不允许同名ACC
if (IsAccExists(newAcc))
return false;
DirectoryEntry userEntry = GetDirectoryEntryByAccount(oldAcc);
userEntry.Properties["sAMAccountName"][0] = newAcc;
userEntry.CommitChanges();
userEntry.Dispose();
return true;
}
else
return false;
}
catch (Exception)
{
return false;
}
}
public static bool SetUserPassword(string userName, string password)
{
try
{
if (SetUserPassword(null, null, userName, password))
return true;
else
return false;
}
catch (Exception ex)
{
return false;
}
}
public static bool SetUserPassword(string adminName, string adminPassword, string userName, string password)
{
adminName = ADUser;
adminPassword = ADPassword;
try
{
DirectoryEntry userEntry = FindObject(adminName, adminPassword, "user", userName);
//userEntry.Properties["userAccountControl"].Value = 544;//0x200;
//userEntry.CommitChanges();
userEntry.Properties["pwdLastSet"].Value =0; // To turn on, set this value to 0.
userEntry.CommitChanges();
userEntry.Invoke("SetPassword", new object[] { password });
userEntry.CommitChanges();
return true;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 删除AD账户,使用当前上下文的安全信息,一般用于Windows程序
/// </summary>
/// <param name="userName">用户名称</param>
/// <returns></returns>
public static bool DeleteADAccount(string Account)
{
//DeleteADAccount(null, null, userName);
if (IsAccExists(Account))
{
string AccPath = GetAccPath(Account);
DetTree(AccPath);
return true;
}
else
return false;
}
/// <summary>
/// 删除AD账户,使用指定的用户名和密码来模拟,一般用于ASP.NET程序
/// </summary>
/// <param name="adminUser">AD管理员用户名,如默认,可以为null</param>
/// <param name="adminPassword">AD管理员密码,如默认,可以为null</param>
/// <param name="userName">用户名称</param>
public static bool DeleteADAccount(string adminUser, string adminPassword, string userName)
{
DirectoryEntry user = null;
DirectoryEntry Container = null;
try
{
adminUser = ADUser;
adminPassword = ADPassword;
user = FindObject(adminUser, adminPassword, "user", userName);
Container = user.Parent;
Container.Children.Remove(user);
Container.CommitChanges();
Container.Dispose();
user.Dispose();
return true;
}
catch (Exception)
{
Container.Dispose();
user.Dispose();
return false;
}
}
/// <summary>
/// 设置用户为解除锁定状态
/// </summary>
/// <param name="accountName"></param>
/// <returns></returns>
public static bool SetADAccountLocked( string accountName)
{
DirectoryEntry user = null;
DirectoryEntry Container = null;
try
{
user = FindObject(ADUser, ADPassword, "user", accountName);
user.Properties["LockOutTime"].Value = 0; //unlock account
user.CommitChanges(); //may not be needed but adding it anyways
user.InvokeSet("IsAccountLocked", false);
user.CommitChanges();
user.Close();
return true;
}
catch (DirectoryServicesCOMException ex)
{
Container.Dispose();
user.Dispose();
return false;
}
}
public static DirectoryEntry FindObject(string category, string name)
{
return FindObject(null, null, category, name);
}
public static DirectoryEntry FindObject(string adminName,
string adminPassword, string category, string name)
{
adminName = ADUser;
adminPassword = ADPassword;
DirectoryEntry de = null;
//if (adminName == null || adminPassword == null)
//{
de = new DirectoryEntry(ADPath, adminName, adminPassword, AuthenticationTypes.Secure);
//}
//else
//{
// de = new DirectoryEntry();
//}
///organizationalUnit
DirectorySearcher ds = new DirectorySearcher(de);
string queryFilter = string.Format("(&(objectCategory=" +
category + ")(sAMAccountName={0}))", name);
ds.Filter = queryFilter;
ds.Sort.PropertyName = "cn";
DirectoryEntry userEntry = null;
try
{
SearchResult sr = ds.FindOne();
userEntry = sr.GetDirectoryEntry();
}
finally
{
if (de != null)
{
de.Dispose();
}
if (ds != null)
{
ds.Dispose();
}
}
return userEntry;
}
#endregion
#region 组织单元操作
/// <summary>
/// 重命名OU
/// </summary>>
/// <param name="oldOUName">原名</param>
/// <param name="newOUName">新名</param>
/// <returns>是否成功</returns>
public static bool RenameOU(string oldOUName, string newOUName)
{
try
{
if (CheckOU(oldOUName))
{
DirectoryEntry userEntry = new DirectoryEntry(GetOrganizeNamePath(oldOUName), ADUser, ADPassword);
userEntry.Rename("OU=" + newOUName);
userEntry.CommitChanges();
userEntry.Dispose();
if (CheckOU(newOUName))
return true;
else
return false;
}
else
return false;
}
catch (Exception)
{
return false;
//throw;
}
}
/// <summary>
/// 检查组织单位(OU)是否存在
/// </summary>
/// <param name="sOU">组织单位名称 </param>
/// <returns>成功返回True,否则返回False</returns>
public static bool CheckOU(string sOU)
{
DirectoryEntry objOU = null;
try
{
objOU = new DirectoryEntry(GetOrganizeNamePath(sOU), ADUser, ADPassword);
string OUName = objOU.Name;
//if (OUName == sOU)
objOU.Close();
objOU = null;
return true;
}
catch
{
objOU.Close();
objOU = null;
return false;
}
}
/// <summary>
/// 创建OU,需要指定连接到AD的授权信息
/// </summary>
/// <param name="adminName"></param>
/// <param name="adminPassword"></param>
/// <param name="name"></param>
/// <param name="parentOrganizeUnit"></param>
public static DirectoryEntry CreateOrganizeUnit(string adminName,
string adminPassword, string name, string parentOrganizeUnit)
{
adminName = ADUser;
adminPassword = ADPassword;
DirectoryEntry parentEntry = null;
if (adminName == null || adminPassword == null)
{
parentEntry = new DirectoryEntry(GetOrganizeNamePath(parentOrganizeUnit));
}
else
{
if (parentOrganizeUnit != "")
{
parentEntry = new DirectoryEntry(GetOrganizeNamePath(parentOrganizeUnit),
adminName, adminPassword,
AuthenticationTypes.Secure);
}
else
{
parentEntry = new DirectoryEntry(GetOrganizeNamePath(parentOrganizeUnit),
adminName, adminPassword,
AuthenticationTypes.Secure);
}
}
DirectoryEntry organizeEntry = parentEntry.Children.Add("OU=" +
name, "organizationalUnit");
organizeEntry.CommitChanges();
return organizeEntry;
}
/// <summary>
/// 创建OU,不需要指定连接到AD的授权信息,用于Windows程序
/// </summary>
/// <param name="name">OU name</param>
/// <param name="parentOrganizeUnit">父OU路径如a/b/c</param>
public static DirectoryEntry CreateOrganizeUnit(string name, string parentOrganizeUnit)
{
return CreateOrganizeUnit(null, null, name, parentOrganizeUnit);
}
/// <summary>
/// 将用户加入到用户组中
/// </summary>
/// <param name="userName">用户名</param>
/// <param name="organizeName">组织名</param>
/// <param name="groupName">组名</param>
/// <exception cref="InvalidObjectException">用户名或用户组不存在</exception>
public static void AddUserToGroup(string userName, string groupName)