Пример #1
0
def process_logs(logdata):
    global args

    for f in args['filters'].split():
        if f:
            if f[:6].lower() == "count:" or f[:6].lower() == "count=":
                args['count'] = abs(int(f[6:]))
            elif f[0] == "-":
                for l in reversed(range(len(logdata))):
                    if f[1:].lower() in str(logdata[l]).lower():
                        del logdata[l]
            else:
                if f[0] == "+": f = f[1:]
                f = str("*" + f + "*").replace("**", "*")
                logdata = fnmatch.filter(logdata, f)

    logdata = logdata[-args['count']:]
    if not args['sort']: logdata = logdata[::-1]

    if args['output'] == "text":
        print "\n".join(logdata)
        sys.exit(0)

    xml = ElementTree.Element('log',
                              log=brandt.strXML(brandt.proper(args['log'])),
                              filters=brandt.strXML(args['filters']))
    for line in logdata:
        xmldata = ElementTree.SubElement(xml, "line")
        xmldata.text = brandt.strXML(line)
    return xml
Пример #2
0
def zarafa_users(users):
  global args, output

  if args['output'] == 'text': output +=  out + '\n'
  if args['output'] != 'xml':
    if not args['delimiter']: args['delimiter'] = "\t"
    output += args['delimiter'].join(headers) + '\n'
    output += "\n".join( [ user.replace(";",args['delimiter']) for user in users ] )
  else:
    data = {}
    xml = ElementTree.Element('users')
    today = datetime.datetime.today()

    for user in users:
      tmp = user.split(';')
      attribs = {}
      logon = None
      logoff = None
      for i in range(len(tmp)):
        if tmp[i]:
          if headers[i] == 'logon':
            logon = datetime.datetime.strptime(tmp[i].decode('unicode_escape'),'%a %b %d %H:%M:%S %Y')
          elif headers[i] == 'logoff':
            logoff = datetime.datetime.strptime(tmp[i].decode('unicode_escape'),'%a %b %d %H:%M:%S %Y')
          else:
            attribs[headers[i]] = brandt.strXML(tmp[i])

      xmluser = ElementTree.SubElement(xml, "user", **attribs)
      if logon:  child = ElementTree.SubElement(xmluser, "logon", lag=brandt.strXML((today - logon).days), date=brandt.strXML(logon))
      if logoff: child = ElementTree.SubElement(xmluser, "logoff", lag=brandt.strXML((today - logoff).days), date=brandt.strXML(logoff))
    return xml
Пример #3
0
def get_data():
    global args
    command = '/usr/sbin/kopano-admin --list-orphans'
    p = subprocess.Popen(command,
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    out, err = p.communicate()
    if err: raise IOError(err)

    orphans = []
    for line in out.strip().split('\n')[3:]:
        tmp = re.sub("\t+", "\t", line).strip().split('\t')
        if line and len(tmp) > 4:
            orphans.append({
                "store": brandt.strXML(tmp[0]),
                "username": brandt.strXML(tmp[1]),
                "logon": brandt.strXML(tmp[2]),
                "size": brandt.strXML(tmp[3]),
                "type": brandt.strXML(tmp[4])
            })
    return orphans
Пример #4
0
def format_users(users):
  global args
  output = ""
  error = ""
  xmldata = ""
  exitcode = 1

  if args['output'] == "text":
    usermaxlen = max( [ len(x) for x in users.keys() ] + [18] )

    for key, label in [ (k, attrsTime[k]['label']) for k in sorted(attrsTime.keys(),key = lambda x: int(attrsTime[x]['min'])) ]:
      tmp = sorted([ u for u in users.keys() if users[u].get(key, 0) > 0 ], key = lambda u: int(users[u][key]), reverse = True)
      if tmp:
        output = str(label).center(usermaxlen + 18) + "\n"
        output += "Username".ljust(usermaxlen) + "  Count" + "\n"
        output += "-" * (usermaxlen + 18) + "\n"
        for u in tmp:
          output += str(u).ljust(usermaxlen) + "  " + str(users[u][key]).rjust(5) + "\n"
        output += "\n"
        
    for user in sorted(users.keys()):
      if users[user].get('samaccountname','') and users[user].get('cn',''):
        output += "User information for " + users[user]['samaccountname'].lower() + " (" + users[user]['cn'] +"):\n" + ("-" * (usermaxlen + 18)) + "\n"
        for key, label in [ (str(k).lower(), attrsLDAP[k]['label']) for k in sorted(attrsLDAP.keys(),key = lambda x: attrsLDAP[x]['sort']) ]:
          if key not in ['cn','samaccountname']:
            output += str(label).rjust(18) + ": " + str(users[user].get(key,"")) + "\n"
        output += "\n"
    exitcode = 0

  elif args['output'] == "csv":
    output  = args['delimiter'].join([ attrsTime[k]['label'] for k in sorted(attrsTime.keys(), key = lambda x: attrsTime[x]['min']) ])
    output += args['delimiter']
    output += args['delimiter'].join([ attrsLDAP[k]['label'] for k in sorted(attrsLDAP.keys(), key = lambda x: attrsLDAP[x]['sort']) ])
    output += "\n"

    attrs = sorted(attrsTime, key = lambda x: attrsTime[x]['min']) + [ a.lower() for a in sorted(attrsLDAP, key = lambda x: attrsLDAP[x]['sort']) ]
    for user in sorted(users.keys()):
      output += user + args['delimiter']
      for attr in attrs:
        output += args['delimiter'] + str(users[user].get(attr,""))
      output += "\n"
    exitcode = 0

  else:

    xmldata = ElementTree.Element('log', log='Login Errors', filters='')
    for user in sorted(users.keys()):
      ElementTree.SubElement(xmldata, "user", **{ k:brandt.strXML(v) for k,v in users[user].items() })
    exitcode = 0

  return output, error, xmldata, exitcode
Пример #5
0
def zarafa_devices(devices):
  global args

  if args['output'] != 'xml':
    if not args['delimiter']: args['delimiter'] = "\t"
    print args['delimiter'].join(headers)
    for device in devices:
      deviceID, username, lastSync = device.split(';')
      print args['delimiter'].join([deviceID, username, lastSync])
    sys.exit(0)

  else:
    xml = ElementTree.Element('devices')
    today = datetime.datetime.today()
    for device in devices:
      deviceID, username, lastSyncText = device.split(';')
      xmldevice = ElementTree.SubElement(xml, "device", deviceid=brandt.strXML(deviceID), username=brandt.strXML(username))
      try:
        lastSync = datetime.datetime.strptime(lastSyncText.decode('unicode_escape'),'%Y-%m-%d %H:%M')
      except:
        lastSync = datetime.datetime.strptime("0001-01-01 00:00".decode('unicode_escape'),'%Y-%m-%d %H:%M')
      child = ElementTree.SubElement(xmldevice, "lastsync", date=brandt.strXML(lastSyncText), lag=brandt.strXML((today - lastSync).days) + '.' + brandt.strXML((today - lastSync).seconds/60) )
    return xml
Пример #6
0
def zarafa_groups(groups):
  global args, output

  if args['output'] == 'text':
    output = "Zarafa Groups (" + str(len(groups)) + ")\n"
    output += "-" * max([len(x) for x in groups] + [13]) + '\n'
    output += "\n".join( groups ) + '\n'
  elif args['output'] == 'csv':
    output = "Zarafa Groups\n"
    output += "\n".join( groups ) + '\n'
  else:
    xml = ElementTree.Element('groups')
    for group in groups:
      xmluser = ElementTree.SubElement(xml, "group", groupname = brandt.strXML(group))
    return xml
Пример #7
0
def zarafa_sessions(sessions):
  global args

  if args['output'] != 'xml':
    if not args['delimiter']: args['delimiter'] = "\t"    
    print args['delimiter'].join(headers)
    print "\n".join( [ session.replace(";",args['delimiter']) for session in sessions ] )
    sys.exit(0)
  else:
    xml = ElementTree.Element('sessions')
    today = datetime.datetime.today()
    for session in sessions:
      tmp = session.split(';')
      attribs = {}
      for i in range(len(tmp)):
        if tmp[i]:
          if i < len(headers):
            attribs[headers[i]] = brandt.strXML(tmp[i])
      xmlsession = ElementTree.SubElement(xml, "session", **attribs)

    return xml
Пример #8
0
                        (today - dates[parameter]['date']).days) + '.' +
                    brandt.strXML(
                        (today - dates[parameter]['date']).seconds / 60))

        return xml


# Start program
if __name__ == "__main__":
    try:
        output = ""
        error = ""
        xmldata = ElementTree.Element('error',
                                      code="-1",
                                      msg="Unknown Error",
                                      cmd=brandt.strXML(" ".join(sys.argv)))
        exitcode = 0

        command_line_args()

        xmldata = zarafa_system(get_data())

    except SystemExit as err:
        pass
    except Exception as err:
        try:
            exitcode = int(err[0])
            errmsg = str(" ".join(err[1:]))
        except:
            exitcode = -1
            errmsg = str(err)
Пример #9
0
def zarafa_device(deviceID, username):
  global args
  command = '/usr/share/z-push/z-push-admin.php -a list -d "' + deviceID + '" -u "' + username + '"'

  p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  out, err = p.communicate()
  if err: raise IOError(err)

  out = out.strip().split("\n")
  error = []
  errors = []

  for c in reversed(range(len(out))):
    line = out[c].lstrip("-")
    if line and line[:17] == 'Attention needed:':
      error = out[c+1:]
      del out[c+1:]
      break

  data = parseData(out)
  for i in reversed(range(len(error))):
    if not error[i]:
      errors.append( parseData(error[i:]) )
      del error[i:]
  if error:
      errors.append( parseData(error[i:]) )

  if args['output'] == 'text':
    width = max( [ len(i[1]) for i in fieldmapping ] ) + 2
    for key, text in fieldmapping:
      if data.has_key(key):
        print (text + ":").rjust(width), data[key]
        if key == "synchronizedbyuser": print "-" * 55
    if errors:
      for error in errors:
        for key, text in errormapping:
          if error.has_key(key):
            print (text + ":").rjust(width), " ", error[key]
        print
    sys.exit(0)
  elif args['output'] == 'csv':
    print args['delimiter'].join( [ i[1] for i in fieldmapping ] )
    print args['delimiter'].join( [ data.get(i[0],"") for i in fieldmapping ] )
    sys.exit(0)
  else:
    xml = ElementTree.Element('devices')
    today = datetime.datetime.today()
    firstsyncText = data.pop("firstsync","never")
    lastsyncText = data.pop("lastsync","never")
    device = ElementTree.SubElement(xml, 'device', **{k:brandt.strXML(v) for k,v in data.items()})

    if firstsyncText:
      try:
        firstsync = datetime.datetime.strptime(firstsyncText.decode('unicode_escape'),'%Y-%m-%d %H:%M')
      except:
        firstsync = datetime.datetime.strptime("0001-01-01 00:00".decode('unicode_escape'),'%Y-%m-%d %H:%M')
      ElementTree.SubElement(device, "firstsync", date=brandt.strXML(firstsyncText), lag=brandt.strXML((today - firstsync).days) + '.' + brandt.strXML((today - firstsync).seconds/60) )
    if lastsyncText:
      try:
        lastsync = datetime.datetime.strptime(lastsyncText.decode('unicode_escape'),'%Y-%m-%d %H:%M')
      except:
        lastsync = datetime.datetime.strptime("0001-01-01 00:00".decode('unicode_escape'),'%Y-%m-%d %H:%M')
      ElementTree.SubElement(device, "lastsync", date=brandt.strXML(lastsyncText), lag=brandt.strXML((today - lastsync).days) + '.' + brandt.strXML((today - lastsync).seconds/60) )

    for error in errors:
      ElementTree.SubElement(device, 'error', **{k:brandt.strXML(v) for k,v in error.items()})
    return xml
Пример #10
0
def zarafa_group(groupname):
    global args, ldapmapping, output
    command = '/usr/sbin/kopano-admin --type group --details "' + str(
        groupname) + '"'

    p = subprocess.Popen(command,
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    out, err = p.communicate()
    if err: raise IOError(err)

    out = str(out).split("\n")
    users = []
    props = []
    for i in reversed(range(len(out))):
        if not out[i]:
            del out[i]
        else:
            if out[i][:7] == "Users (":
                users = out[i:]
                del out[i:]
            elif out[i] == "Mapped properties:":
                props = out[i:]
                del out[i:]
    del users[0:3]
    users = [(str(str(x).split('\t')[1]), ''.join(str(x).split('\t')[2:]))
             for x in users]
    users = sorted(users, key=lambda s: s[0].lower())

    del props[0]
    props = [(str(str(x).split('\t')[1]).lower(),
              ''.join(str(x).split('\t')[2:])) for x in props]
    props = {x[0]: x[1] for x in props}

    out = [(str(str(x).split('\t')[0]).lower().replace(" ",
                                                       "").replace(":", ""),
            ''.join(str(x).split('\t')[1:])) for x in out]
    data = {x[0]: x[1] for x in out}
    data.update(props)

    command = '/usr/sbin/kopano-admin --type group --list-sendas "' + str(
        groupname) + '"'
    p = subprocess.Popen(command,
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    out, err = p.communicate()
    if err: raise IOError(err)
    sendas = [str(x).split("\t") for x in str(out).split("\n")[3:] if x]

    if args['output'] == "text":
        if not args['delimiter']: args['delimiter'] = "\t"
        width = max([len(x[1]) for x in fieldmappings] +
                    [len(x[1]) + 2 for x in ldapfieldmappings]) + 1
        for key, text in fieldmappings:
            output = str(text +
                         ":").ljust(width) + args['delimiter'] + data.get(
                             key, '') + '\n'
        output += "Mapped properties:\n"
        for key, text in ldapfieldmappings:
            output += str("  " + text +
                          ":").ljust(width) + args['delimiter'] + data.get(
                              key, '') + '\n'
        if sendas:
            tmp = [x[1] + "(" + x[2] + ")" for x in sendas]
            output += "\nSend As Rights (" + str(len(sendas)) + "):\n"
            output += '-' * (width + 10) + '\n'
            output += brandt.printTable(sorted(tmp), 2) + '\n'
        if users:
            output += "Users (" + str(len(users)) + "):\n"
            widths = [
                max([len(x[0]) for x in users]) + 2,
                max([len(x[1]) for x in users])
            ]
            output += "  " + "Username".ljust(
                widths[0]) + args['delimiter'] + "Full Name".ljust(
                    widths[1]) + '\n'
            output += "  " + "-" * (sum(widths) + 5) + '\n'
            for user in users:
                output += "  " + user[0].ljust(
                    widths[0]) + args['delimiter'] + user[1].ljust(
                        widths[1]) + '\n'
    elif args['output'] == "csv":
        tmp = []
        if sendas:
            tmp.append("Send As Rights")
            for i in range(1, len(sendas)):
                tmp.append('')
        if users:
            tmp.append("Users")
            for i in range(1, len(groups)):
                tmp.append('')
        output = args['delimiter'].join([x[1]
                                         for x in fieldmappings] + tmp) + '\n'
        tmp = []
        if sendas: tmp += sorted([x[1] + "(" + x[2] + ")" for x in sendas])
        if groups: tmp += sorted(groups)
        output += args['delimiter'].join(
            [data.get(x[0], "") for x in fieldmappings] + tmp) + '\n'
    else:
        xml = ElementTree.Element('groups')
        xmlgroup = ElementTree.SubElement(
            xml, "group", **{k: brandt.strXML(v)
                             for k, v in data.items()})
        for send in sendas:
            ElementTree.SubElement(xmlgroup,
                                   'sendas',
                                   username=brandt.strXML(send[1]),
                                   fullname=brandt.strXML(send[2]))
        for user in users:
            ElementTree.SubElement(xmlgroup,
                                   'user',
                                   username=brandt.strXML(user[0]),
                                   fullname=brandt.strXML(user[1]))
        return xml
Пример #11
0
  return (zarafaChanged, date, combinedEmails)

# Start program
if __name__ == "__main__":
  try:
    output = ""
    error = ""
    exitcode = 0    
    xmldata = None

    command_line_args()  
    zarafaChanged, date, emails = get_data()

    if args['web']:
      xmldata = ElementTree.Element('emails', **{'date': brandt.strXML(datetime.datetime.strftime(date,'%Y-%m-%d %H:%M:%S'))})
      for email in sorted(emails.keys()):
        ElementTree.SubElement(xmldata, 'email', **{'mail': brandt.strXML(email), 
                                        'zarafa': brandt.strXML(emails[email]['zarafa']), 
                                        'domino': brandt.strXML(emails[email]['domino']), 
                                        'forward': brandt.strXML(emails[email]['forward']),
                                        'username': brandt.strXML(emails[email]['username']),
                                        'type': brandt.strXML(emails[email]['type'])})
    else:
      if zarafaChanged or args['force']:
        output += brandt.syslog("Changes detected: Running Zarafa Sync\n", options=['pid'])
        command = '/usr/sbin/zarafa-admin --sync'
        p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = p.communicate()
        if err: raise IOError(err)
        output += out + "\n"
Пример #12
0
                              filters=brandt.strXML(args['filters']))
    for line in logdata:
        xmldata = ElementTree.SubElement(xml, "line")
        xmldata.text = brandt.strXML(line)
    return xml


# Start program
if __name__ == "__main__":
    try:
        output = ""
        error = ""
        xmldata = ElementTree.Element('error',
                                      code="-1",
                                      msg="Unknown Error",
                                      cmd=brandt.strXML(" ".join(sys.argv)))
        exitcode = 0

        command_line_args()

        if args['list']:
            if args['output'] != 'xml':
                output = "\n".join([
                    str(k) + ", " + str(logDefaults[k]['logfile'])
                    for k in logDefaults.keys()
                ])
            else:
                xmldata = ElementTree.Element('logs')
                for k in logDefaults.keys():
                    ElementTree.SubElement(xmldata,
                                           "log",
Пример #13
0
    # if not args['message']: args['message'] = get_input("Enter message: ")

    # if not args['user']: args['user'] = get_input("Enter your user name: ")
    if not args['pass']:
        args['pass'] = get_input("Enter your password: "******"password")


# Start program
if __name__ == "__main__":
    # try:
    output = ""
    error = ""
    xmldata = ElementTree.Element('error',
                                  code="-1",
                                  msg="Unknown Error",
                                  cmd=brandt.strXML(" ".join(sys.argv)))
    exitcode = 0

    command_line_args()

    if args['action'] == "ooo":
        process_ooo()
    elif args['action'] == "ooo-enable":
        process_ooo_enable()
    elif args['action'] == "ooo-disable":
        process_ooo_disable()
    elif args['action'] == "hook":
        process_hook()
    elif args['action'] == "unhook":
        process_unhook()
Пример #14
0
				pass

	except SystemExit as err:
		pass
	except Exception as err:
		try:
			exitcode = int(err[0])
			errmsg = str(" ".join(err[1:]))
		except:
			exitcode = -1
			errmsg = str(err)

		if args['output'] != 'xml': 
			error = "(" + str(exitcode) + ") " + str(errmsg) + "\nCommand: " + " ".join(sys.argv)
		else:
			xmldata = ElementTree.Element('error', code=brandt.strXML(exitcode), 
																						 msg=brandt.strXML(errmsg), 
																						 cmd=brandt.strXML(" ".join(sys.argv)))
	finally:
		if args['output'] == 'xml':
			xml = ElementTree.Element('updates-available', **updates)
			if xmldata: xml.append(xmldata)
			print '<?xml version="1.0" encoding="' + encoding + '"?>\n' + ElementTree.tostring(xml, encoding=encoding, method="xml")
		else:
			if error:
				sys.stderr.write( str(error) + "\n" )

			elif args['output'] == 'text':
				print updates['total'], 'packages can be updated.'
				print updates['security'], 'updates are security updates.'
			elif args['output'] == 'csv':
Пример #15
0
def get_ldap(LDAPURI):
  # try:
    return brandt.LDAPSearch(LDAPURI).resultsDict(functDN=lambda dn: brandt.strXML(brandt.formatDN(dn)),
                                                  functAttr=lambda a: brandt.strXML(str(a).lower()), 
                                                  functValue=lambda *v:brandt.strXML(brandt.formatDN(v[-1])))
Пример #16
0
def zarafa_system(data):
    global args

    if args['output'] == 'csv':
        print args['delimiter'].join([line.split(";")[0] for line in data])
        print args['delimiter'].join([line.split(";")[2] for line in data])
        sys.exit(0)

    elif args['output'] == 'text':
        if not args['delimiter']: args['delimiter'] = "\t"
        width = max([len(line.split(";")[1]) for line in data])
        for line in data:
            parameter, desc, value = line.split(";")
            if parameter in [
                    'server_start_date', 'cache_purge_date',
                    'config_reload_date', 'sql_last_fail_time'
            ]:
                if value:
                    value = str(
                        datetime.datetime.strptime(
                            value.decode('unicode_escape'),
                            '%a %b %d %H:%M:%S %Y'))
            print str(desc).ljust(width) + args['delimiter'] + str(value)
        sys.exit(0)

    else:
        attrib = {}
        dates = {}

        for line in data:
            parameter, desc, value = line.split(";")
            if parameter in [
                    'server_start_date', 'cache_purge_date',
                    'config_reload_date', 'sql_last_fail_time'
            ]:
                try:
                    dates[parameter] = {}
                    dates[parameter]['text'] = value
                    dates[parameter]['date'] = datetime.datetime.strptime(
                        value.decode('unicode_escape'), '%a %b %d %H:%M:%S %Y')
                except:
                    dates[parameter] = {}
                    dates[parameter]['text'] = value
                    dates[parameter]['date'] = datetime.datetime.strptime(
                        "0001-01-01 00:00".decode('unicode_escape'),
                        '%Y-%m-%d %H:%M')

            else:
                attrib[parameter] = brandt.strXML(value)

        xml = ElementTree.Element('system', **attrib)
        today = datetime.datetime.today()
        for parameter in [
                'server_start_date', 'cache_purge_date', 'config_reload_date',
                'sql_last_fail_time'
        ]:
            if dates.has_key(parameter) and dates[parameter].get('text', ""):
                ElementTree.SubElement(
                    xml,
                    parameter,
                    date=brandt.strXML(dates[parameter]['text']),
                    lag=brandt.strXML(
                        (today - dates[parameter]['date']).days) + '.' +
                    brandt.strXML(
                        (today - dates[parameter]['date']).seconds / 60))

        return xml
Пример #17
0
                "logon": brandt.strXML(tmp[2]),
                "size": brandt.strXML(tmp[3]),
                "type": brandt.strXML(tmp[4])
            })
    return orphans


# Start program
if __name__ == "__main__":
    try:
        output = ""
        error = ""
        xmldata = ElementTree.Element('error',
                                      code="-1",
                                      msg="Unknown Error",
                                      cmd=brandt.strXML(" ".join(sys.argv)))
        exitcode = 0

        command_line_args()

        orphans = get_data()

        if args['output'] == 'text':
            if not args['delimiter']: args['delimiter'] = "\t"
            orphans.insert(
                0, {
                    "store": "Store GUID",
                    "username": "******",
                    "logon": "Last Logon",
                    "size": "Store Size",
                    "type": "Store Type"
Пример #18
0
def get_data():
    global args, attrsTime, attrsLDAP
    cachefile = '/tmp/kopano-logins.cache'

    args['cache'] *= 60
    age = args['cache'] + 1
    try:
        age = (datetime.datetime.now() - datetime.datetime.fromtimestamp(
            os.stat(cachefile).st_mtime)).seconds
    except:
        pass

    if age > args['cache']:
        command = 'grep "Authentication by plugin failed for user" "/var/log/zarafa/server.log"'
        p = subprocess.Popen(command,
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        out, err = p.communicate()
        if err: raise IOError(err)
        users = {}

        # Troll the logs to find users failed logins and count the occurances
        for line in out.split('\n'):
            try:
                now = datetime.datetime.now()
                tmp = line.replace("  ", " ").replace(" ", ":").split(":")
                tmpTime = datetime.datetime(int(tmp[6]),
                                            months.index(tmp[1].lower()),
                                            int(tmp[2]), int(tmp[3]),
                                            int(tmp[4]), int(tmp[5]))
                tmpUser = tmp[-1].lower()
                if not users.has_key(tmpUser):
                    users[tmpUser] = {'user': tmp[-1]}
                for attr in attrsTime.keys():
                    if tmpTime > now - datetime.timedelta(
                            minutes=attrsTime[attr]['min']):
                        users[tmpUser].update(
                            {attr: users[tmpUser].get(attr, 0) + 1})
            except:
                pass

        # Remove users who's login failures occurred too long ago and convert integer values to strings
        for user in users.keys():
            if len(users[user]) == 1:
                del users[user]
            else:
                for attr in attrsTime.keys():
                    if users[user].has_key(attr):
                        users[user][attr] = str(users[user][attr])

        # Retrieve LDAP values for remaining users
        for user in users.keys():
            try:
                ldapURI = args['scheme'] + "://" + args['server'] + "/"
                ldapURI += args['base'] + "?" + ",".join(attrsLDAP.keys(
                )) + "?" + args['scope'] + "?sAMAccountName=" + user
                results = brandt.LDAPSearch(ldapURI).results
                if str(results[0][1]['sAMAccountName'][0]).lower() == user:
                    for key in results[0][1]:
                        try:
                            value = results[0][1][key][0]
                            key = key.lower()
                            if key in [
                                    'badpasswordtime', 'lastlogoff',
                                    'lastlogon', 'pwdlastset',
                                    'lastlogontimestamp', 'accountexpires'
                            ]:
                                value = str(
                                    datetime.datetime(1601, 1, 1) +
                                    datetime.timedelta(
                                        microseconds=(int(value) / 10)))[:19]
                                if value == '1601-01-01 00:00:00':
                                    value = 'never'
                            elif key == 'logonhours':
                                tmp = ""
                                for char in value:
                                    tmp += str(hex(ord(char))[2:]).upper()
                                value = tmp
                            users[user][key] = brandt.strXML(value)
                        except:
                            pass
            except:
                pass

        attrs = sorted(attrsTime, key=lambda x: attrsTime[x]['min']) + [
            a.lower()
            for a in sorted(attrsLDAP, key=lambda x: attrsLDAP[x]['sort'])
        ]
        f = open(cachefile, 'w')
        for user in sorted(users.keys()):
            f.write(user)
            for attr in attrs:
                f.write("," + str(users[user].get(attr, "")))
            f.write("\n")
        f.close()
    else:
        f = open(cachefile, 'r')
        out = f.read().strip().split('\n')
        f.close()

        users = {}
        for line in out:
            if line:
                c = 0
                line = line.split(",")
                user = str(line[c]).lower()
                tmp = {"user": line[c]}
                attrs = sorted(
                    attrsTime, key=lambda x: attrsTime[x]['min']) + [
                        a.lower()
                        for a in sorted(attrsLDAP,
                                        key=lambda x: attrsLDAP[x]['sort'])
                    ]
                for attr in attrs:
                    c += 1
                    if str(line[c]): tmp[attr] = str(line[c])
                users[user] = tmp.copy()

    return users
Пример #19
0
    try:
      p = subprocess.Popen(mdmCMD + " --output xml", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
      mdmSTR, err = p.communicate()
      if err: raise IOError(err)
      xmluser.append(ElementTree.fromstring(mdmSTR).find('devices'))
    except:
      pass

    return xml

# Start program
if __name__ == "__main__":
  try:
    output = ""
    error = ""
    xmldata = ElementTree.Element('error', code="-1", msg="Unknown Error", cmd=brandt.strXML(" ".join(sys.argv)))
    exitcode = 0

    command_line_args()  
    users = get_data()
    if len(users) == 1:
      xmldata = zarafa_user(users[0].split(";")[headers.index("username")])
    else:
      xmldata = zarafa_users(users)

  except SystemExit as err:
    pass
  except Exception as err:
    try:
      exitcode = int(err[0])
      errmsg = str(" ".join(err[1:]))
Пример #20
0
# Start program
if __name__ == "__main__":
    try:
        output = ""
        error = ""
        exitcode = 0
        xmldata = None

        command_line_args()
        zarafaChanged, date, emails = get_data()

        if args['web']:
            xmldata = ElementTree.Element(
                'emails', **{
                    'date':
                    brandt.strXML(
                        datetime.datetime.strftime(date, '%Y-%m-%d %H:%M:%S'))
                })
            for email in sorted(emails.keys()):
                ElementTree.SubElement(
                    xmldata, 'email', **{
                        'mail': brandt.strXML(email),
                        'zarafa': brandt.strXML(emails[email]['zarafa']),
                        'domino': brandt.strXML(emails[email]['domino']),
                        'forward': brandt.strXML(emails[email]['forward']),
                        'username': brandt.strXML(emails[email]['username']),
                        'type': brandt.strXML(emails[email]['type'])
                    })
        else:
            if zarafaChanged or args['force']:
                output += brandt.syslog(
                    "Changes detected: Running Zarafa Sync\n", options=['pid'])
Пример #21
0
def zarafa_user(username):
  global args, ldapmapping, output
  command = '/usr/sbin/kopano-admin --type user --details "' + str(username) + '"'

  p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  out, err = p.communicate()
  if err: raise IOError(err)

  data = str(out).split("\n")
  groups = []
  quotas = []
  props = []
  output = ""  
  for i in reversed(range(len(data))):
    if not data[i]: 
      del data[i]
    else:
      if data[i][:8] == "Groups (":
        groups = data[i:]
        del data[i:]
      elif data[i] == "Current user store quota settings:":
        quotas = data[i:]
        del data[i:]
      elif data[i] == "Mapped properties:":
        props = data[i:]
        del data[i:]

  del groups[0]
  groups = [ str(x).lower().strip() for x in groups ]
  groups.remove("everyone")

  props = [ (str(str(x).split('\t')[1]).lower(), ''.join(str(x).split('\t')[2:])) for x in props[1:] ]
  props = { x[0]:x[1] for x in props }

  data += quotas[1:]
  data = [ str(x).replace(":",":\t",1) for x in data ]
  data = [ ( str(str(x).split('\t')[0]).lower().replace(" ","").replace(":","").replace("-",""), ''.join(str(x).split('\t')[1:]) ) for x in data ]
  data = { x[0]:x[1] for x in data }
  data.update(props)

  data["username"] = data.get("username","").lower()
  data["emailaddress"] = data.get("emailaddress","").lower()
  if data.has_key("warninglevel"): data["warninglevel"] = "{:.0f}".format(float(data.get("warninglevel","").split(" ")[0]) * 1024)
  if data.has_key("softlevel"): data["softlevel"] = "{:.0f}".format(float(data.get("softlevel","").split(" ")[0]) * 1024)
  if data.has_key("hardlevel"): data["hardlevel"] = "{:.0f}".format(float(data.get("hardlevel","").split(" ")[0]) * 1024)
  if data.has_key("currentstoresize"): data["currentstoresize"] = "{:.0f}".format(float(data.get("currentstoresize","").split(" ")[0]) * 1048576)
  logon = None
  if data.has_key("lastlogon"):
    try:
      logon = datetime.datetime.strptime(data.get("lastlogon").decode('unicode_escape'),'%d/%m/%y %H:%M:%S')
    except:
      logon = datetime.datetime.strptime(data.get("lastlogon").decode('unicode_escape'),'%m/%d/%y %H:%M:%S')
    finally:
      data["lastlogon"] = str(logon)
  logoff = None
  if data.has_key("lastlogoff"):
    try:
      logoff = datetime.datetime.strptime(data.get("lastlogoff").decode('unicode_escape'),'%d/%m/%y %H:%M:%S')
    except:
      logoff = datetime.datetime.strptime(data.get("lastlogoff").decode('unicode_escape'),'%m/%d/%y %H:%M:%S')
    finally:
      data["lastlogoff"] = str(logoff)

  for good,bad in ldapmapping:
    if data.has_key(bad):
      data[good] = data[bad]
      del data[bad]

  command = '/usr/sbin/kopano-admin --type user --list-sendas "' + str(username) + '"'
  p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  out, err = p.communicate()
  if err: raise IOError(err)
  sendas = [ str(x).split("\t") for x in str(out).split("\n")[3:] if x ]
 
  mdmCMD = '/opt/brandt/ZarafaAdmin/bin/zarafa-mdm.py --user "' + str(username) + '"'
  if args['output'] == "text":
    maxlen = max([ len(f[1]) for f in fieldmappings ] + [ len(f[1]) for f in quotafieldmappings ] + [ len(f[1]) for f in ldapfieldmappings if data.has_key(f[0]) ] )
    maxlen += 2
    for key,text in fieldmappings:
      output += (text + ":").ljust(maxlen), data.get(key,"") + '\n'

    output += 'Mapped properties:\n'
    for key,text in ldapfieldmappings:
      if data.has_key(key):
        output +=  (" " + text + ":").ljust(maxlen), data[key] + '\n'

    output +=  "Current user store quota settings:\n"
    for key,text in quotafieldmappings:
      output +=  (text + ":").ljust(maxlen), data.get(key,"") + '\n'

    if sendas:
      tmp = [ x[1] + "(" + x[2] + ")" for x in sendas ]
      output +=  "\nSend As Rights (" + str(len(sendas)) + "):" + '\n'
      output +=  '-' * (maxlen + 10) + '\n'
      brandt.printTable(sorted(tmp),2)
      
    if groups:
      output += "\nGroups (" + str(len(groups)) + "):" + '\n'
      output += '-' * (maxlen + 10) + '\n'
      brandt.printTable(sorted(groups),2)

    p = subprocess.Popen(mdmCMD + " --output text", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    mdmSTR, err = p.communicate()
    if err: raise IOError(err)
    mdmLEN = len(mdmSTR.split("\n")) - 2
    if mdmLEN < 0: mdmLEN = 0
    output += "\nMobile Devices (" + str(mdmLEN) + "):" + '\n'
    output += '-' * (maxlen + 10) + '\n'
    output += mdmSTR + '\n'

    sys.exit(0)

  elif args['output'] == "csv":
    tmp = []
    if sendas:
      tmp.append("Send As Rights")
      for i in range(1,len(sendas)): tmp.append('')
    if groups:
      tmp.append("Groups")
      for i in range(1,len(groups)): tmp.append('')
    output += args['delimiter'].join([ f[1] for f in (fieldmappings + quotafieldmappings) ] + tmp) + '\n'

    tmp = []
    if sendas: tmp += sorted([ x[1] + "(" + x[2] + ")" for x in sendas ])
    if groups: tmp += sorted(groups)
    output += args['delimiter'].join([ data.get(f[0],"") for f in (fieldmappings + quotafieldmappings ) ] + tmp ) + '\n'

    sys.exit(0)

  else:
    if data.has_key("lastlogon"): del data["lastlogon"]
    if data.has_key("lastlogoff"): del data["lastlogoff"]

    xml = ElementTree.Element('users')
    today = datetime.datetime.today()
    xmluser = ElementTree.SubElement(xml, "user", **{k:brandt.strXML(v) for k,v in data.items()})
    if logon:  child = ElementTree.SubElement(xmluser, "logon", lag=brandt.strXML((today - logon).days), date=brandt.strXML(logon))
    if logoff: child = ElementTree.SubElement(xmluser, "logoff", lag=brandt.strXML((today - logoff).days), date=brandt.strXML(logoff))
    for send in sendas:
      ElementTree.SubElement(xmluser, 'sendas', username = brandt.strXML(send[1]), fullname = brandt.strXML(send[2]))
    for group in groups:
      ElementTree.SubElement(xmluser, 'group', groupname = brandt.strXML(group))

    try:
      p = subprocess.Popen(mdmCMD + " --output xml", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
      mdmSTR, err = p.communicate()
      if err: raise IOError(err)
      xmluser.append(ElementTree.fromstring(mdmSTR).find('devices'))
    except:
      pass

    return xml
Пример #22
0
def get_ldap(LDAPURI):
    # try:
    return brandt.LDAPSearch(LDAPURI).resultsDict(
        functDN=lambda dn: brandt.strXML(brandt.formatDN(dn)),
        functAttr=lambda a: brandt.strXML(str(a).lower()),
        functValue=lambda *v: brandt.strXML(brandt.formatDN(v[-1])))