Advertisement
Guest User

Untitled

a guest
Jan 11th, 2016
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. #! /usr/bin/python3
  2.  
  3. """
  4. Script that quickly initializes a MySQL database and account for use in dev
  5. environments
  6. """
  7.  
  8. import argparse
  9. from string import ascii_uppercase, digits
  10. from random import choice
  11. from cymysql import connect
  12.  
  13.  
  14. DB_HOST = 'localhost'
  15. DB_USER = 'root'
  16. DB_PASS = 'your_password'
  17. LIMIT_CONNECTION_TO = 'localhost'
  18.  
  19.  
  20. def main():
  21. parser = argparse.ArgumentParser(description=
  22. "Creates a new MySQL database and user " +
  23. "fast use in development environment")
  24. parser.add_argument('-n', '--name', help="Name of the application. This " +
  25. "will be used as user and db name",
  26. required=True)
  27. args = parser.parse_args()
  28.  
  29. name = args.name
  30.  
  31. # Generating a new password
  32. password = ''.join(choice(ascii_uppercase + digits) for _ in range(6))
  33.  
  34. # Script for creating the user
  35. create_user = "CREATE USER '{}'@'{}' IDENTIFIED BY '{}'".format(
  36. name, LIMIT_CONNECTION_TO, password
  37. )
  38.  
  39. create_database = "CREATE DATABASE %s" % name
  40.  
  41. grant = "GRANT ALL ON %s.* TO '%s'@'%s'" % (name, name, LIMIT_CONNECTION_TO)
  42.  
  43. connection = connect(DB_HOST, DB_USER, DB_PASS)
  44. cursor = connection.cursor()
  45. cursor.execute(create_user)
  46. cursor.execute(create_database)
  47. cursor.execute(grant)
  48. connection.close()
  49.  
  50. print("The password for the created user is %s" % password)
  51.  
  52. if __name__ == '__main__':
  53. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement