<commit_before>#!/usr/bin/env python

import urwid
import urwid.raw_display
import urwid.web_display
import logging
import sys
import re
import crypt
import subprocess
from fuelmenu.settings import *
from fuelmenu.common import network, puppet, replace, \
    nailyfactersettings, dialog
from fuelmenu.common.urwidwrapper import *
log = logging.getLogger('fuelmenu.rootpw')
blank = urwid.Divider()

fields = ["PASSWORD", "CONFIRM_PASSWORD"]

DEFAULTS = {
    "PASSWORD": {"label": "Enter password",
                 "tooltip": "Use ASCII characters only",
                 "value": ""},
    "CONFIRM_PASSWORD": {"label": "Confirm password",
                         "tooltip": "Use ASCII characters only",
                          "value": ""},
    }


class rootpw(urwid.WidgetWrap):
    def __init__(self, parent):
        self.name = "Root Password"
        self.priority = 60
        self.visible = True
        self.parent = parent
        self.screen = None

    def check(self, args):
        """Validate that all fields have valid values and some sanity checks"""
        self.parent.footer.set_text("Checking data...")
        self.parent.refreshScreen()
        #Get field information
        responses = dict()

        for index, fieldname in enumerate(fields):
            if fieldname == "blank":
                pass
            else:
                responses[fieldname] = self.edits[index].get_edit_text()

        ###Validate each field
        errors = []

        #Passwords must match
        if responses["PASSWORD"] != responses["CONFIRM_PASSWORD"]:
            errors.append("Passwords do not match.")

        #password must not be empty
        if len(responses["PASSWORD"]) == 0:
            errors.append("Password must not be empty.")

        #password needs to be in ASCII character set
        try:
            asciipw = responses["PASSWORD"].decode('ascii')
        except UnicodeDecodeError:
            errors.append("Password contains non-ASCII characters.")

        if len(errors) > 0:
            self.parent.footer.set_text(
                "Errors: %s First error: %s" % (len(errors), errors[0]))
            return False
        else:
            self.parent.footer.set_text("No errors found.")
            return responses

    def apply(self, args):
        responses = self.check(args)
        if responses is False:
            log.error("Check failed. Not applying")
            log.error("%s" % (responses))
            if responses["PASSWORD"] == "":
                #Empty password means user didn't enter any text
                return True
            return False

        hashed = crypt.crypt(responses["PASSWORD"])
        log.info("Changing root password")
        try:
            #clear any locks first
            noop = subprocess.call(["rm", "-f", "/etc/passwd.lock",
                                    "/etc/shadow.lock"], stdout=noout,
                                    stderr=noout)
            retcode = subprocess.call(["usermod", "-p", hashed, "root"],
                                      stdout=noout,
                                      stderr=noout)
        except OSError:<commit_msg>fix output for suprocess.call<commit_after>#!/usr/bin/env python

import urwid
import urwid.raw_display
import urwid.web_display
import logging
import sys
import re
import crypt
import subprocess
from fuelmenu.settings import *
from fuelmenu.common import network, puppet, replace, \
    nailyfactersettings, dialog
from fuelmenu.common.urwidwrapper import *
log = logging.getLogger('fuelmenu.rootpw')
blank = urwid.Divider()

fields = ["PASSWORD", "CONFIRM_PASSWORD"]

DEFAULTS = {
    "PASSWORD": {"label": "Enter password",
                 "tooltip": "Use ASCII characters only",
                 "value": ""},
    "CONFIRM_PASSWORD": {"label": "Confirm password",
                         "tooltip": "Use ASCII characters only",
                          "value": ""},
    }


class rootpw(urwid.WidgetWrap):
    def __init__(self, parent):
        self.name = "Root Password"
        self.priority = 60
        self.visible = True
        self.parent = parent
        self.screen = None

    def check(self, args):
        """Validate that all fields have valid values and some sanity checks"""
        self.parent.footer.set_text("Checking data...")
        self.parent.refreshScreen()
        #Get field information
        responses = dict()

        for index, fieldname in enumerate(fields):
            if fieldname == "blank":
                pass
            else:
                responses[fieldname] = self.edits[index].get_edit_text()

        ###Validate each field
        errors = []

        #Passwords must match
        if responses["PASSWORD"] != responses["CONFIRM_PASSWORD"]:
            errors.append("Passwords do not match.")

        #password must not be empty
        if len(responses["PASSWORD"]) == 0:
            errors.append("Password must not be empty.")

        #password needs to be in ASCII character set
        try:
            asciipw = responses["PASSWORD"].decode('ascii')
        except UnicodeDecodeError:
            errors.append("Password contains non-ASCII characters.")

        if len(errors) > 0:
            self.parent.footer.set_text(
                "Errors: %s First error: %s" % (len(errors), errors[0]))
            return False
        else:
            self.parent.footer.set_text("No errors found.")
            return responses

    def apply(self, args):
        responses = self.check(args)
        if responses is False:
            log.error("Check failed. Not applying")
            log.error("%s" % (responses))
            if responses["PASSWORD"] == "":
                #Empty password means user didn't enter any text
                return True
            return False

        hashed = crypt.crypt(responses["PASSWORD"])
        log.info("Changing root password")
        try:
            #clear any locks first
            noout = open('/dev/null', 'w')
            noop = subprocess.call(["rm", "-f", "/etc/passwd.lock",
                                    "/etc/shadow.lock"], stdout=noout,
                                    stderr=noout)
            retcode = subprocess.call(["usermod", "-p", hashed, "root"],
                                      stdout=noout,
                                      stderr=noout)
        except OSError:
{'fraction_non_alphanumeric': 0.1103804603100047, 'fraction_numerical': 0.001565680288085173, 'mean_word_length': 1.8658591296545537, 'pattern_counts': {'":': 20, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5198178', 'n_tokens_mistral': 1719, 'n_tokens_neox': 1638, 'n_words': 461}