Last active
May 16, 2023 09:32
-
-
Save jonathanhle/4bb44d2e5d3ace8a62928ec2cb3e39a7 to your computer and use it in GitHub Desktop.
pritunl mongodb query for user info
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Requires pymongo 3.6.0+ | |
from datetime import datetime, timedelta | |
from pymongo import MongoClient | |
from bson.tz_util import FixedOffset | |
from bson.son import SON | |
from collections import OrderedDict | |
# Setup logger | |
import logging | |
import logging.handlers | |
import syslog | |
logger = logging.getLogger('myLogger') | |
logger.setLevel(logging.INFO) | |
#add handler to the logger | |
handler = logging.handlers.SysLogHandler(address = '/dev/log') | |
#add formatter to the handler | |
formatter = logging.Formatter('%(module)s.%(funcName)s: %(message)s') | |
handler.setFormatter(formatter) | |
logger.addHandler(handler) | |
# Get 5 minutes previous ISO | |
fiveminutespast = (datetime.now() - timedelta(minutes=5)).strftime("%Y-%m-%d %H:%M:%S.%f") | |
client = MongoClient("mongodb://{{ mongodb_host }}:{{ mongodb_port }}/", document_class=OrderedDict) | |
database = client["pritunl"] | |
collection = database["users_audit"] | |
pipeline = [ | |
{ | |
u"$lookup": { | |
u"from": u"users", | |
u"localField": u"user_id", | |
u"foreignField": u"_id", | |
u"as": u"matched_user" | |
} | |
}, | |
{ | |
u"$unwind": { | |
u"path": u"$matched_user" | |
} | |
}, | |
{ | |
u"$match": { | |
u"timestamp": { | |
u"$gte": datetime.strptime(fiveminutespast, "%Y-%m-%d %H:%M:%S.%f").replace(tzinfo = FixedOffset(0, "+0000")) | |
} | |
} | |
}, | |
{ | |
u"$project": { | |
u"_id": 0.0, | |
u"user_id": 1.0, | |
u"remote_addr": 1.0, | |
u"timestamp": 1.0, | |
u"org_id": 1.0, | |
u"message": 1.0, | |
u"type": 1.0, | |
u"matched_user.auth_type": 1.0, | |
u"matched_user.name": 1.0, | |
u"matched_user.type": 1.0, | |
u"matched_user.email": 1.0 | |
} | |
}, | |
{"$sort": SON([("count", -1), ("_id", -1)])} | |
] | |
cursor = collection.aggregate( | |
pipeline, | |
allowDiskUse = False | |
) | |
try: | |
for doc in cursor: | |
logger.info(doc) | |
# All output goes to syslog; uncomment the following line to troubleshoot | |
# print(doc) | |
finally: | |
client.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
fetching pritunl audit records and putting them in syslog, so another system would pick up the logs