Ejemplo n.º 1
0
 def getActiveUser(self):
     user = "******"
     try:
         domain = ""
         sessionId = GetActiveSessionId()
         if sessionId != 0xffffffff:
             user = win32ts.WTSQuerySessionInformation(
                 win32ts.WTS_CURRENT_SERVER_HANDLE, sessionId,
                 win32ts.WTSUserName)
             domain = win32ts.WTSQuerySessionInformation(
                 win32ts.WTS_CURRENT_SERVER_HANDLE, sessionId,
                 win32ts.WTSDomainName)
         if domain == "":
             pass
         elif domain.lower() != self.getMachineName().lower():
             # Use FQDN as user name if computer is part of a domain.
             try:
                 user = u"%s\\%s" % (domain, user)
                 user = win32security.TranslateName(
                     user, win32api.NameSamCompatible,
                     win32api.NameUserPrincipal)
                 # Check for error because no exception is raised when
                 # running under Windows XP.
                 err = win32api.GetLastError()
                 if err != 0:
                     raise RuntimeError(err, 'TranslateName')
             except:
                 logging.exception("Error on user name translation.")
         else:
             user = u"%s@%s" % (user, domain)
     except:
         logging.exception("Error retrieving active user name.")
     logging.debug("Active user: %s", user)
     return user
Ejemplo n.º 2
0
def main():
    global verbose
    _handlers_dict = {}

    arg_descs = []
    for arg, func in handlers:
        this_desc = "\n".join(textwrap.wrap(func.__doc__,
                                            subsequent_indent = " " * 8))
        arg_descs.append("  %s: %s" % (arg, this_desc))
        _handlers_dict[arg.lower()] = func

    description = __doc__ + "\ncommands:\n" + "\n".join(arg_descs) + "\n"

    parser = optparse.OptionParser(usage = "%prog [options] command ...",
                                   description=description,
                                   formatter=HelpFormatter())

    parser.add_option("-v", action="count",
                      dest="verbose", default=1,
                      help="increase the verbosity of status messages")

    parser.add_option("-q", "--quiet", action="store_true",
                      help="Don't print any status messages")

    parser.add_option("-t", "--test", action="store_true",
                      help="Execute a mini-test suite, providing defaults for most options and args"),

    parser.add_option("", "--show-tracebacks", action="store_true",
                      help="Show the tracebacks for any exceptions")

    parser.add_option("", "--service-class",
                      help="The service class name to use")

    parser.add_option("", "--port", default=0,
                      help="The port number to associate with the SPN")

    parser.add_option("", "--binding-string",
                      help="The binding string to use for SCP creation")

    parser.add_option("", "--account-name",
                      help="The account name to use (default is LocalSystem)")

    parser.add_option("", "--password",
                      help="The password to set.")

    parser.add_option("", "--keyword", action="append", dest="keywords",
                      help="""A keyword to add to the SCP.  May be specified
                              multiple times""")

    parser.add_option("", "--log-level",
                      help="""The log-level to use - may be a number or a logging
                             module constant""", default=str(logging.WARNING))

    options, args = parser.parse_args()
    po = (parser, options)
    # fixup misc
    try:
        options.port = int(options.port)
    except (TypeError, ValueError):
        parser.error("--port must be numeric")
    # fixup log-level
    try:
        log_level = int(options.log_level)
    except (TypeError, ValueError):
        try:
            log_level = int(getattr(logging, options.log_level.upper()))
        except (ValueError, TypeError, AttributeError):
            parser.error("Invalid --log-level value")
    try:
        sl = logger.setLevel
        # logger is a real logger
    except AttributeError:
        # logger is logging module
        sl = logging.getLogger().setLevel
    sl(log_level)
    # Check -q/-v
    if options.quiet and options.verbose:
        parser.error("Can't specify --quiet and --verbose")
    if options.quiet:
        options.verbose -= 1
    verbose = options.verbose
    # --test
    if options.test:
        if args:
            parser.error("Can't specify args with --test")
    
        args = "ScpDelete ScpCreate SpnCreate SpnRegister SpnUnregister ScpDelete"
        log(1, "--test - pretending args are:\n %s", args)
        args = args.split()
        if not options.service_class:
            options.service_class = "PythonScpTest"
            log(2, "--test: --service-class=%s", options.service_class)
        if not options.keywords:
            options.keywords = "Python Powered".split()
            log(2, "--test: --keyword=%s", options.keywords)
        if not options.binding_string:
            options.binding_string = "test binding string"
            log(2, "--test: --binding-string=%s", options.binding_string)

    # check args
    if not args:
        parser.error("No command specified (use --help for valid commands)")
    for arg in args:
        if arg.lower() not in _handlers_dict:
            parser.error("Invalid command '%s' (use --help for valid commands)" % arg)

    # Patch up account-name.
    if options.account_name:
        log(2, "Translating account name '%s'", options.account_name)
        options.account_name_sam = win32security.TranslateName(options.account_name,
                                                               win32api.NameUnknown,
                                                               win32api.NameSamCompatible)
        log(2, "NameSamCompatible is '%s'",options.account_name_sam)
        options.account_name_dn = win32security.TranslateName(options.account_name,
                                                               win32api.NameUnknown,
                                                               win32api.NameFullyQualifiedDN)
        log(2, "NameFullyQualifiedDNis '%s'",options.account_name_dn)

    # do it.
    for arg in args:
        handler = _handlers_dict[arg.lower()] # already been validated
        if handler is None:
            parser.error("Invalid command '%s'" % arg)
        err_msg = None
        try:
            try:
                log(2, "Executing '%s'...", arg)
                result = handler(po)
                log(1, "%s: %s", arg, result)
            except:
                if options.show_tracebacks:
                    print("--show-tracebacks specified - dumping exception")
                    traceback.print_exc()
                raise
        except adsi.error as xxx_todo_changeme:
            (hr, desc, exc, argerr) = xxx_todo_changeme.args
            if exc:
                extra_desc = exc[2]
            else:
                extra_desc = ""
            err_msg = desc
            if extra_desc:
                err_msg += "\n\t" + extra_desc
        except win32api.error as xxx_todo_changeme1:
            (hr, func, msg) = xxx_todo_changeme1.args
            err_msg = msg
        if err_msg:
            log(1, "Command '%s' failed: %s", arg, err_msg)
Ejemplo n.º 3
0
 def _testTranslate(self, fmt_from, fmt_to):
     name = win32api.GetUserNameEx(fmt_from)
     expected = win32api.GetUserNameEx(fmt_to)
     got = win32security.TranslateName(name, fmt_from, fmt_to)
     self.failUnlessEqual(got, expected)
Ejemplo n.º 4
0
 def _testTranslate(self, fmt_from, fmt_to):
     name = win32api.GetUserNameEx(fmt_from)
     expected = win32api.GetUserNameEx(fmt_to)
     got = win32security.TranslateName(name, fmt_from, fmt_to)
     assert got == expected