Best Python code snippet using autotest_python
mysql_secure_installation.py
Source:mysql_secure_installation.py  
1#!/usr/bin/python2# -*- coding: utf-8 -*-3# Copyright: (c) 2020, eslam.gomaa <linkedin.com/in/eslam-sa3dany>4DOCUMENTATION = '''5---6module: mysql_secure_installation7short_description: An idempotent module to perform "mysql_secure_installation" script steps8version_added: "1.0"9description:10    - An idempotent module to perform "mysql_secure_installation" script steps11        - Change MySQL Root Password - for a list of hosts i.e [localhost, 127.0.0.1, ::1,] .etc.12        - Remove Anonymous User13        - Disallow Root Login Remotely14        - Remove Test Database15options:16    login_password:17        description:18            - Root's password to login to MySQL	19        required: true20        type: str21        22    new_password:23        description:24            - New desired Root password25        required: true26        type: str27    user:28        description:29            - MySQL user to login30        default: "root"31        type: str32                33    login_host:34        description:35            - host to connect to36        default: "localhost"37        type: str38    hosts:39        description:40            - List of hosts for the provided user i.e ['localhost', '127.0.0.1', '::1'], Note - all will have the same new password41        default: ["localhost"]42        type: list43    change_root_password:44        description:45            - whether or not to change root password 46        default: True47        type: bool48        49    remove_anonymous_user:50        description:51            - whether or not to remove anonymous user 52        default: True53        type: bool54        55    disallow_root_login_remotely:56        description:57            - whether or not to disallow root login remotely58        default: False59        type: bool60        61    remove_test_db:62        description:63            - whether or not to remove test db64        default: True65        type: bool66 67author:68    - eslam.gomaa (linkedin.com/in/eslam-sa3dany)69'''70EXAMPLES = '''71# with a fresh MySQL Installation72- name: test mysql_secure_installation73  mysql_secure_installation:74    login_password: ''75    new_password: password2276    user: root77    login_host: localhost78    hosts: ['localhost', '127.0.0.1', '::1']79    change_root_password: true80    remove_anonymous_user: true81    disallow_root_login_remotely: true82    remove_test_db: true83  register: mysql_secure84- debug:85    var: mysql_secure86# Change an existing password87- name: test mysql_secure_installation88  mysql_secure_installation:89    login_password: password2290    new_password: password2391    user: root92    login_host: localhost93    hosts: ['localhost', '127.0.0.1', '::1']94    change_root_password: true95    remove_anonymous_user: true96    disallow_root_login_remotely: true97    remove_test_db: true98'''99RETURN = '''100change_root_pwd:101    description: 0 == Success, 1 == Fail102    type: Int103    returned: always104disallow_root_remotely:105    description: 0 == Success, 1 == Fail106    type: Int107    returned: always108hosts_success:109    description: provides a list of the hosts succeeded to change password to i.e ['root@localhost', 'root@mysql.example.com']110    type: List111    returned: always112hosts_failed:113    description: provides a list of the hosts failed to change password to i.e ['root@localhost', 'root@mysql.example.com']114    type: List115    returned: always116remove_anonymous_user:117    description: 0 == Success, 1 == Fail118    type: Int119    returned: always120remove_test_db:121    description: 0 == Success, 1 == Fail122    type: Int123    returned: always124stdout:125    description: Prints the result of the code as compared to the desired state126    type: Str127    returned: always128stderr:129    description: Prints an error message in case of code error130    type: Str131    returned: In case of code error132'''133##############################################134#######################135############136import MySQLdb as mysql137from itertools import chain138def check_mysql_connection(host, user, password=''):139    """140    A function used to check the ability to login to MySQL/Mariadb141    :param host: ie. 'localhost'  - :type String142    :param user: mysql user ie. 'root' - :type String143    :param password: mysql user's password - :type String144    :return: True||False145    """146    try:147        mysql.connect(host=host, user=user, passwd=password)148        return True149    except  mysql.Error:150        return False151def mysql_secure_installation(login_password, new_password, user='root',login_host='localhost', hosts=['hostname'], change_root_password= True, remove_anonymous_user= True, disallow_root_login_remotely= False, remove_test_db= True):152    """153    A function to perform the steps of mysql_secure_installation script154    :param login_password: Root's password to login to MySQL155    :param new_password: New desired Root password :type String156    :param user: MySQL user - default: 'root' :type String157    :param login_host: host to connect to - default: 'localhost' :type String158    :param hosts: List of hosts for the provided user i.e ['localhost', '127.0.0.1', '::1'] :type List159    :param change_root_password:  default: True - :type Boolean160    :param remove_anonymous_user: default: True - :type: Boolean161    :param disallow_root_login_remotely: default: False - :type Boolean162    :param remove_test_db: default: True - :type: Boolean163    :return:164    """165    if isinstance(hosts, str):166        hosts = hosts.split(',')167    info = {'change_root_pwd': None, 'hosts_failed': [], 'hosts_success': [],'remove_anonymous_user': None, 'remove_test_db': None, 'disallow_root_remotely': None }168    def remove_anon_user(cursor):169        if remove_anonymous_user:170            cursor.execute("select user, host from mysql.user where user='';")171            anon_user = cursor.fetchall()172            if len(anon_user) >= 1:173                cursor.execute('use mysql;')174                cursor.execute("DELETE FROM user WHERE user='';")175                cursor.execute("update mysql.user set plugin=null where user='root';")176                cursor.execute("select user, host from mysql.user where user='';")177                check = cursor.fetchall()178                if len(check) >= 1:179                    info['remove_anonymous_user'] = 1180                else:181                    info['remove_anonymous_user'] = 0182            else:183                info['remove_anonymous_user'] = 0184    def remove_testdb(cursor):185        if remove_test_db:186            cursor.execute("show databases;")187            testdb = cursor.fetchall()188            if 'test' in list(chain.from_iterable(testdb)): # if database "test" exists in the "db's list"189                cursor.execute("drop database test;")190                cursor.execute("show databases;") # Test if the "test" db deleted191                check_test_db = cursor.fetchall()192                if 'test' in list(chain.from_iterable(check_test_db)): # return 1 if the db still exists193                    info['remove_test_db'] = 1194                else:195                    info['remove_test_db'] = 0196            else: # means "test" db does not exist197                info['remove_test_db'] = 0198    def disallow_root_remotely(cursor):199        if disallow_root_login_remotely:200            cursor.execute("select user, host from mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');")201            remote = cursor.fetchall()202            if len(remote) >= 1:203                cursor.execute("DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');")204                cursor.execute("flush privileges;")205                cursor.execute("select user, host from mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');")206                check_remote = cursor.fetchall()207                if len(check_remote) >= 1: # test208                    info['disallow_root_remotely'] = 1209                else:210                    info['disallow_root_remotely'] = 0211            else:212                info['disallow_root_remotely'] = 0213    if check_mysql_connection(host=login_host, user=user, password=login_password):214        try:215            connection = mysql.connect(host=login_host, user=user, passwd=login_password, db='mysql')216            cursor = connection.cursor()217            cursor.execute("SELECT host, user, password, plugin FROM mysql.user where User='{}' LIMIT 0,1;".format(user))218            socket_exists = cursor.fetchall()219            if 'unix_socket' in list(chain.from_iterable(socket_exists)):220                cursor.execute("UPDATE mysql.user SET plugin = '' WHERE user = {};".format(user))221            remove_anon_user(cursor)222            remove_testdb(cursor)223            disallow_root_remotely(cursor)224            if change_root_password:225                pwd = {}226                for host in hosts:227                    cursor.execute('use mysql;')228                    cursor.execute(229                        'update user set password=PASSWORD("{}") where User="{}" AND Host="{}";'.format(new_password,230                                                                                                        user, host))231                    cursor.execute('flush privileges;')232                    cursor.execute('select user, host, password from mysql.user where user="{}";'.format(user))233                    data = cursor.fetchall()234                    for d in data:235                        if d[1] == host:236                            pwd['{}'.format(d[1])] = d[2]237                out = set(hosts).symmetric_difference(set(pwd.keys()))238                info['hosts_failed'] = list(out)239                hosts_ = list(set(hosts) - set(list(out)))240                for host in hosts_:241                    if pwd[host] == pwd[login_host]:242                        info['hosts_success'].append(host)243                    else:244                        info['hosts_failed'].append(login_host)245                if len(info['hosts_success']) >= 1:246                    info['stdout'] = 'Password for user: {} @ Hosts: {} changed to the desired state'.format(user, info['hosts_success'])247                if len(info['hosts_failed']) >= 1:248                    info['change_root_pwd'] = 1249                #    info['stderr'] = 'Could NOT change password for User: {} @ Hosts: {}'.format(user,info['hosts_failed'])250                else:251                    info['change_root_pwd'] = 0252            connection.close()253        except mysql.Error as e:254            info['change_root_pwd'] = 1255            info['stderr'] = e256    elif check_mysql_connection(host=login_host, user=user, password=new_password):257        connection = mysql.connect(host=login_host, user=user, passwd=new_password, db='mysql')258        cursor_ = connection.cursor()259        remove_anon_user(cursor_)260        remove_testdb(cursor_)261        disallow_root_remotely(cursor_)262        info['change_root_pwd'] = 0263        info['stdout'] = 'Password of {}@{} Already meets the desired state'.format(user, login_host)264    else:265        info['change_root_pwd'] = 1266        info['stdout'] = 'Neither the provided old passwd nor the new passwd are correct'267    return info268############269#######################270##############################################271from ansible.module_utils.basic import *272def main():273    fields = {274        "login_password": {"required": True, "type": "str", "no_log": True},275        "new_password": {"required": True, "type": "str", "no_log": True},276        "user": {"type": "str", "default": "root"},277        "login_host": {"type": "str", "default": "localhost"},278        "hosts": {"type": "list", "default": ["localhost"]},279        "change_root_password": {"type": "bool", "default": True, "choices": [True, False]},280        "remove_anonymous_user": {"type": "bool", "default": True, "choices": [True, False]},281        "disallow_root_login_remotely": {"type": "bool", "default": False, "choices": [True, False]},282        "remove_test_db": {"type": "bool", "default": True, "choices": [True, False]},283    }284    module = AnsibleModule(argument_spec=fields)285    run = mysql_secure_installation(login_password=module.params['login_password'],286                              new_password=module.params['new_password'],287                              user=module.params['user'],288                              login_host=module.params['login_host'],289                              hosts=module.params['hosts'],290                              change_root_password=module.params['change_root_password'],291                              remove_anonymous_user=module.params['remove_anonymous_user'],292                              disallow_root_login_remotely=module.params['disallow_root_login_remotely'],293                              remove_test_db=module.params['remove_test_db'])294    if run["change_root_pwd"] == 1 and len(run["hosts_failed"]) == 0:295        module.warn('mysql_secure_installation --> Neither the provided old passwd nor the new passwd are correct -- Skipping')296    if len(run["hosts_success"]) >= 1:297        changed_ = True298    else:299        changed_ = False300    module.exit_json(changed=changed_, meta=run)301if __name__ == '__main__':...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
