Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
mongo_parsing.py
import argparse
fqdn = "domain.com"
def mongo_by_url(uri):
uri_pieces = uri.split(":")
data = {
"user": uri_pieces[1].replace("//", ""),
"password": uri_pieces[2].split("@")[0],
"server": uri_pieces[2].split("@")[1],
"port": uri_pieces[3][:uri_pieces[3].find("/")],
"database": uri_pieces[3][uri_pieces[3].find("=")+1:]
}
print(data["user"])
print(data["password"])
print(data["server"])
print(data["port"])
print(data["database"])
print("")
mongo_by_data(data)
def mongo_by_data(data):
uri = "mongodb://{0}:{1}@{2}.{3}:{4}/?authSource={5}".format(data["user"], data["password"], data["server"], fqdn, data["port"],
data["database"])
print("use {0}".format(data["database"]))
print("""
db.createUser(
{{ user: "{0}",
pwd: "{1}",
roles: [
{{ role: "readWrite", db: "{2}" }}
]
}}
)
""".format(data["user"], data["password"], data["database"]))
file = open(data["database"] + "_" + data["server"] + ".json", "w")
output = """
{{
"database": "{0}",
"uri": "{1}"
}}
""".format(data["database"], uri)
print(output)
print(uri)
file.writelines(output)
file.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser(add_help=True)
group = parser.add_mutually_exclusive_group()
parser.add_argument('-d', '--database', required=False, help='specify the database name')
group.add_argument('-u', '--user', required=False, help='specify the username.')
parser.add_argument('-pw', '--password', required=False, help='specify the user password')
parser.add_argument('-s', '--server', required=False, help='specify the server')
parser.add_argument('-p', '--port', required=False, default="27017", help='optional: specify the port - 27017 will be used by default')
group.add_argument('-url', help='uri - if uri is specified no other parameters should be used')
args = parser.parse_args()
if args.port:
port = args.port
else:
port = "27017"
if args.user:
d = {
"user": args.user,
"password": args.password,
"server": args.server,
"database": args.database,
"port": port
}
if args.url:
mongo_by_url(args.url)
else:
mongo_by_data(d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.