[Python] Generare le impostazioni MySQL per WordPress

Nel tutorial di oggi vi mostreremo come creare uno script python che genera automaticamente le impostazioni MySQL per il file di configurazione "wp-config.php" di WordPress.

  1.  
  2. #!/usr/bin/python
  3. import string
  4. import random
  5. import sys
  6. import MySQLdb
  7.  
  8. # pass_gen will generate a random string of characters
  9.  
  10.  
  11. def pass_gen(size=10,
  12. chars=string.ascii_uppercase +
  13. string.ascii_lowercase +
  14. string.digits):
  15. return ''.join(random.choice(chars) for x in range(size))
  16.  
  17.  
  18. def main(argv):
  19. sitename = argv[0]
  20.  
  21. '''
  22. Generate semi-random names
  23. Random number is based off of 16 minus the length of databse name given
  24. '''
  25.  
  26. db_name = sitename + pass_gen(16 - len(sitename))
  27. db_user = sitename + pass_gen(16 - len(sitename))
  28. db_password = sitename + pass_gen(16 - len(sitename))
  29.  
  30. # Create the database with the settings
  31. db = MySQLdb.connect(host='localhost', user='root', passwd='Superb33')
  32. cur = db.cursor()
  33.  
  34. create_db_sql = 'CREATE DATABASE %s' % (db_name)
  35. grant_user_sql = 'GRANT ALL PRIVILEGES ON %s.* to "%s"@"localhost" \
  36. identified by "%s"' % (db_name, db_user, db_password)
  37. cur.execute(create_db_sql)
  38. cur.execute(grant_user_sql)
  39.  
  40. # Concatnate DB Strings
  41. db_name_string = "/** The name of the database for WordPress */\
  42. \ndefine('DB_NAME', '%s');\n" % (db_name)
  43. db_user_string = "/** MySQL database username */\
  44. \ndefine('DB_USER', '%s');\n" % (db_user)
  45. db_pass_string = "/** MySQL database password */\
  46. \ndefine('DB_PASSWORD', '%s');\n" % (db_password)
  47.  
  48. # Print the result
  49. print "Copy and paste this to the wp-config.php settings file\n"
  50. print db_name_string
  51. print db_user_string
  52. print db_pass_string
  53.  
  54. if __name__ == "__main__":
  55. main(sys.argv[1:])
  56.