Created
March 16, 2018 12:57
-
-
Save ceeblet/9187f4b0ac7fe82a3e46da4a331ce15c to your computer and use it in GitHub Desktop.
mongo_parsing.py
This file contains 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
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