Advertisement
Guest User

Untitled

a guest
Apr 26th, 2017
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import MySQLdb
  4. from getpass import getpass
  5.  
  6.  
  7. def get_connection():
  8. while True:
  9. passwd = getpass("Enter root password:")
  10. try:
  11. return MySQLdb.connect("localhost", "root", passwd, "mysql")
  12. except:
  13. print("Invalid password.")
  14.  
  15.  
  16. def get_user(c):
  17. while True:
  18. user = input("Enter the user name: ").strip()
  19. num_rows = c.execute("SELECT 1 FROM user WHERE user = %(user)s", { 'user': user })
  20.  
  21. if num_rows > 0:
  22. print("This user already exists. Try again.")
  23. else:
  24. return user
  25.  
  26.  
  27. def get_schema(default):
  28. return input("Enter the schema name (default: {}): ".format(default)).strip() or default
  29.  
  30.  
  31. def get_passwd():
  32. while True:
  33. passwd = getpass("Enter the password for the new user")
  34. if not passwd:
  35. print("Invalid password.")
  36. else:
  37. return passwd
  38.  
  39.  
  40. if __name__ == "__main__":
  41. conn = get_connection()
  42. c = conn.cursor()
  43.  
  44. user = get_user(c)
  45. schema = get_schema(default=user)
  46. passwd = get_passwd()
  47.  
  48. sql = """
  49. CREATE SCHEMA IF NOT EXISTS {0}
  50. DEFAULT CHARACTER SET = utf8mb4
  51. DEFAULT COLLATE = utf8mb4_general_ci
  52. ;
  53. CREATE USER %(user)s@'localhost' IDENTIFIED BY %(passwd)s;
  54. GRANT ALL PRIVILEGES ON {0}.* TO %(user)s@'localhost';
  55. FLUSH PRIVILEGES;
  56. """.format(schema)
  57. success = c.execute(sql, locals())
  58.  
  59. print("-")
  60. if success:
  61. print("The user/schema pair was created!")
  62. else:
  63. print("There was an error... :(")
  64.  
  65. conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement