Skip to content

Instantly share code, notes, and snippets.

@languanghao
Created September 17, 2014 07:21

Revisions

  1. languanghao created this gist Sep 17, 2014.
    25 changes: 25 additions & 0 deletions Convert Active Directory SID to string
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@

    def convert_sid_tostring(sid_str):
    """
    将SID转换成正常的字符串,形如:S-1-5-21-3146574646-1373620345-747391786-4398
    :param sid_str: AD返回的SID
    :return: str
    """
    sid_bytes = list(bytearray(sid_str))
    sid_str = list(sid_str)
    sid = 'S-%d' % sid_bytes[0]
    if sid_bytes[6] != 0 or sid_bytes[5] != 0:
    raise Exception('AD的认证方式无法识别')
    else:
    ival = sid_bytes[1] + (sid_bytes[2] << 8) + (sid_bytes[3] << 16) + (sid_bytes[4] << 24)
    sid = sid + '-' + str(ival)
    print sid
    iSubCount = sid_bytes[7]
    for i in range(iSubCount):
    idxAuth = 8 + i * 4
    end = idxAuth + 4
    temp = sid_str[idxAuth:end]
    q = ''.join(temp)
    iSubAuth = struct.unpack('I', q)
    sid = sid + '-' + str(iSubAuth[0])
    return sid