How can I get the domain name for a user logged into a Mac via Active Directory

旧街凉风 提交于 2020-01-02 02:56:05

问题


In my Cocoa app how can I get the current user's domain when they're logged in via Active Directory?

I need to determine two things:

  1. If the current user is logged on to an Active Directory domain (only need to handle Active Directory).
  2. If 1, the domain of the user.

I've found references to Directory Services and the Open Directory Programming Guide but the latter is 10.6 only (I must support 10.5+) and I could not find any examples for the former that gave me an idea of what I needed to do.


回答1:


dsconfigad -show

It will tell whether you are bound to a directory and details about that directory if bound. Then you will know how to script dscl.




回答2:


I think you can use same idea as here:

Mac OSX: Determing whether user account is an Active Directory user vs. local user using objective-c

you just need to look for Network or Authentication node (it's kODNodeTypeAuthentication type) and query it for kODAttributeTypeRecordName with query value set to current user name. Then look at search result, you'll find many interesting things there :)




回答3:


You can use this code, but note that I assume that you refer to the user that is running the current application, if you are running as root, it won't work. In case you run it as root, simply change the NSUserName() in the query to the desired user you wish to query.

std::string getDomainForCurrentUser()
{
    ODSession *session = [ODSession defaultSession];
    ODNode *node = [ODNode nodeWithSession:session type:kODNodeTypeAuthentication error:NULL];
    ODQuery *query = [ODQuery queryWithNode:node forRecordTypes:kODRecordTypeUsers attribute:kODAttributeTypeRecordName matchType:kODMatchEqualTo queryValues:NSUserName() returnAttributes:kODAttributeTypeStandardOnly maximumResults:0 error:NULL];
    NSArray *records = [query resultsAllowingPartial:NO error:NULL];

    for (ODRecord *record in records)
    {
        NSArray *recordLines = [record valuesForAttribute:kODAttributeTypePrimaryNTDomain error:nil];

        if (recordLines)
        {
            NSString *domain = [recordLines firstObject];
            std::string([domain UTF8String]);

        }
    }

    return "";
}


来源:https://stackoverflow.com/questions/2953378/how-can-i-get-the-domain-name-for-a-user-logged-into-a-mac-via-active-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!