Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- import MySQLdb
- from getpass import getpass
- def get_connection():
- while True:
- passwd = getpass("Enter root password:")
- try:
- return MySQLdb.connect("localhost", "root", passwd, "mysql")
- except:
- print("Invalid password.")
- def get_user(c):
- while True:
- user = input("Enter the user name: ").strip()
- num_rows = c.execute("SELECT 1 FROM user WHERE user = %(user)s", { 'user': user })
- if num_rows > 0:
- print("This user already exists. Try again.")
- else:
- return user
- def get_schema(default):
- return input("Enter the schema name (default: {}): ".format(default)).strip() or default
- def get_passwd():
- while True:
- passwd = getpass("Enter the password for the new user")
- if not passwd:
- print("Invalid password.")
- else:
- return passwd
- if __name__ == "__main__":
- conn = get_connection()
- c = conn.cursor()
- user = get_user(c)
- schema = get_schema(default=user)
- passwd = get_passwd()
- sql = """
- CREATE SCHEMA IF NOT EXISTS {0}
- DEFAULT CHARACTER SET = utf8mb4
- DEFAULT COLLATE = utf8mb4_general_ci
- ;
- CREATE USER %(user)s@'localhost' IDENTIFIED BY %(passwd)s;
- GRANT ALL PRIVILEGES ON {0}.* TO %(user)s@'localhost';
- FLUSH PRIVILEGES;
- """.format(schema)
- success = c.execute(sql, locals())
- print("-")
- if success:
- print("The user/schema pair was created!")
- else:
- print("There was an error... :(")
- conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement