示例#1
0
def main():
    global LOGGER_NAME
    parser = argparse.ArgumentParser(description='Create a server certificate using the cacerts db.')
    parser.add_argument('--loglevel', help='Specify the default logging level (optional).', choices=['debug', 'info', 'warning', 'error', 'DEBUG', 'INFO', 'WARNING', 'ERROR'], default='info')
    parser.add_argument('--debug', help='turn on debug output', action='store_true', default=False)
    parser.add_argument('--logfile', help='Specify logfile name.', default='/tmp/gen_known_hosts.log')
    parser.add_argument('--server_host', help='specify the server hostname we are adding a known_hosts entry for.', default='localhost')
    parser.add_argument('--server_port', help='specify the server port number we are adding a known_hosts entry for.', default=29418, type=int)
    parser.add_argument('--check_exists', help='just check if the first account exist, if it does not, then return 1, if it does return 0', action='store_true', default=False)
    args = parser.parse_args()
    if args.debug:
        args.loglevel = 'debug'
    logger = setup_logging(args.logfile, args.loglevel, LOGGER_NAME)
    banner_start()
    logger.debug("parsed arguments")
    logger.debug("adding known_hosts entry for " + args.server_host + ":" + str(args.server_port))
    user_home = get_ux_home()
    logger.debug("current user home = " + user_home)
    create_ssh_folder(user_home)
    if not os.path.isfile(os.path.join(user_home, '.ssh', 'known_hosts')):
        logger.debug("create known_hosts file with key scan results")
        key_scan_res = scan_host_key(args.server_host, args.server_port)
        write_text_tofile(os.path.join(user_home, '.ssh', 'known_hosts'), key_scan_res)
        logger.info(os.path.join(user_home, '.ssh', 'known_hosts') + " created.")
    else:
        if not file_contains_text(os.path.join(user_home, '.ssh', 'known_hosts'), '^' + str(get_ip_from_host(args.server_host))):
            logger.debug("file already exist, adding key to file")
            key_scan_res = scan_host_key(args.server_host, args.server_port)
            write_text_tofile(os.path.join(user_home, '.ssh', 'known_hosts'), key_scan_res)
            logger.info(os.path.join(user_home, '.ssh', 'known_hosts') + " appended.")
        else:
            logger.info(os.path.join(user_home, '.ssh', 'known_hosts') + " already setup.")
    banner_end()
    return 0
示例#2
0
def main():
    global LOGGER_NAME
    # http://docs.python.org/2/library/argparse.html
    parser = argparse.ArgumentParser(description='Create a server certificate using the cacerts db.')
    parser.add_argument('--loglevel', help='Specify the default logging level (optional).', choices=['debug', 'info', 'warning', 'error', 'DEBUG', 'INFO', 'WARNING', 'ERROR'], default='info')
    parser.add_argument('--logfile', help='Specify logfile name.', default='/tmp/createfirstaccount.log')
    parser.add_argument('--debug', help='turn on debug output', action='store_true', default=False)
    parser.add_argument('--working_dir', help='working directory.', default='/tmp')
    parser.add_argument('--username', help='change default user name to create as first account.', default='gerrit2')
    parser.add_argument('--email', help='specify the email address for the user.', default='*****@*****.**')
    parser.add_argument('--ssh_pubkey', help='pupblic key to use. Example, generate with :\n ssh-keygen -t rsa  -f ~/.ssh/gerrit2 -P ""', default='/home/gerrit2/.ssh/gerrit2.pub')
    parser.add_argument('--check_exists', help='just check if the first account exist, if it does not, then return 1, if it does return 0', action='store_true', default=False)
    args = parser.parse_args()
    if args.debug:
        args.loglevel = 'debug'
    logger = setup_logging(args.logfile, args.loglevel, LOGGER_NAME)
    banner_start()
    logger.debug("parsed arguments")
    # check that we have an ssh key
    try:
        if not os.path.isfile(args.ssh_pubkey):
            throws('No ssh public key found : ' + args.ssh_pubkey)
    except Exception, err:
        logger.error("Problem in file check : " + str(err))
        return 300
示例#3
0
def main():
    global LOGGER_NAME
    # http://docs.python.org/2/library/argparse.html
    parser = argparse.ArgumentParser(description='run gerrit gsql commands from yaml.')
    parser.add_argument('--loglevel', help='Specify the default logging level (optional).', choices=['debug', 'info', 'warning', 'error', 'DEBUG', 'INFO', 'WARNING', 'ERROR'], default='info')
    parser.add_argument('--logfile', help='Specify logfile name.', default='/tmp/gerrit_runsql.log')
    parser.add_argument('--loggername', help='Specify a name for the logger.', default=LOGGER_NAME)
    parser.add_argument('--debug', help='turn on debug output', action='store_true', default=False)
    parser.add_argument('--working_dir', help='working directory.', default='/tmp')
    parser.add_argument('--onlyif_not_hasrows', help='only run if the sql does not have rows.', default='')
    parser.add_argument('--check', help='only echo sql we will execute, do not run it', action='store_true', default=False)
    parser.add_argument('--sql_config_file', help='change default user name to create as first account.', default='/tmp/gerrit_init.sql.yaml')
    args = parser.parse_args()
    if args.debug:
        args.loglevel = 'debug'
    LOGGER_NAME = args.loggername
    logger = setup_logging(args.logfile, args.loglevel, LOGGER_NAME)
    banner_start()
    logger.debug("parsed arguments")

    # check to see that we can connect
    if not gsql_exec('select @@version')[0] == 0:
        banner_end_fail()
        return 1

    retval = [0, '0 rows']
    if args.onlyif_not_hasrows != "":
        retval = gsql_exec(args.onlyif_not_hasrows)
        if not retval[0] == 0:
            logger.error("onlyif_not_hasrows check failed: " + retval[1])
            logger.error("attempted to run sql: " + args.onlyif_not_hasrows)
            banner_end_fail()
            return 1
    else:
        logger.debug("not performing pre-execution check.")

    if not retval[1].upper().rstrip('\n').find('0 ROWS') >= 0:
        logger.info("onlyif_not_hasrows found rows, do nothing.")
        banner_end()
        return 0

    f = open(args.sql_config_file)
    dataMap = yaml.safe_load(f)
    f.close()

    for sql in dataMap['gsql']:
        logger.info("gsql executing : " + sql)
        if not args.check:
            retval = gsql_exec(sql)
            if not retval[0] == 0:
                logger.error("Failed to process gsql: " + retval[1])
                banner_end_fail()
                return 1
        else:
            logger.warn("skipping exec, check is on")
    banner_end()
    return 0
示例#4
0
def main():
    global LOGGER_NAME
    # http://docs.python.org/2/library/argparse.html
    parser = argparse.ArgumentParser(
        description='Create a server certificate using the cacerts db.')
    parser.add_argument('--loglevel',
                        help='Specify the default logging level (optional).',
                        choices=[
                            'debug', 'info', 'warning', 'error', 'DEBUG',
                            'INFO', 'WARNING', 'ERROR'
                        ],
                        default='info')
    parser.add_argument('--logfile',
                        help='Specify logfile name.',
                        default='/tmp/createfirstaccount.log')
    parser.add_argument('--debug',
                        help='turn on debug output',
                        action='store_true',
                        default=False)
    parser.add_argument('--working_dir',
                        help='working directory.',
                        default='/tmp')
    parser.add_argument(
        '--username',
        help='change default user name to create as first account.',
        default='gerrit2')
    parser.add_argument('--email',
                        help='specify the email address for the user.',
                        default='*****@*****.**')
    parser.add_argument(
        '--ssh_pubkey',
        help=
        'pupblic key to use. Example, generate with :\n ssh-keygen -t rsa  -f ~/.ssh/gerrit2 -P ""',
        default='/home/gerrit2/.ssh/gerrit2.pub')
    parser.add_argument(
        '--check_exists',
        help=
        'just check if the first account exist, if it does not, then return 1, if it does return 0',
        action='store_true',
        default=False)
    args = parser.parse_args()
    if args.debug:
        args.loglevel = 'debug'
    logger = setup_logging(args.logfile, args.loglevel, LOGGER_NAME)
    banner_start()
    logger.debug("parsed arguments")
    # check that we have an ssh key
    try:
        if not os.path.isfile(args.ssh_pubkey):
            throws('No ssh public key found : ' + args.ssh_pubkey)
    except Exception, err:
        logger.error("Problem in file check : " + str(err))
        return 300
示例#5
0
def main():
    global LOGGER_NAME
    # http://docs.python.org/2/library/argparse.html
    parser = argparse.ArgumentParser(
        description='Creates Gerrit Admin Accounts')
    parser.add_argument('--loglevel',
                        help='Specify the default logging level (optional).',
                        choices=[
                            'debug', 'info', 'warning', 'error', 'DEBUG',
                            'INFO', 'WARNING', 'ERROR'
                        ],
                        default='info')
    parser.add_argument('--logfile',
                        help='Specify logfile name.',
                        default='/tmp/create_admin.log')
    parser.add_argument('--debug',
                        help='turn on debug output',
                        action='store_true',
                        default=False)
    parser.add_argument('--working_dir',
                        help='working directory.',
                        default='/tmp')
    parser.add_argument(
        '--username',
        help='change default user name to create as first account.',
        default='')
    parser.add_argument('--email',
                        help='specify the email address for the user.',
                        default='')
    parser.add_argument(
        '--claimed_id',
        help=
        'specify the claimed id, example: https://login.launchpad.net/+id/MJA3AHw',
        default='')
    # parser.add_argument('--ssh_pubkey', help='pupblic key to use. Example, generate with :\n ssh-keygen -t rsa  -f ~/.ssh/gerrit2 -P ""', default='/home/gerrit2/.ssh/gerrit2.pub')
    parser.add_argument(
        '--check_exists',
        help='checks if the account exists 0 == exists, 1 == not exists',
        action='store_true',
        default=False)
    args = parser.parse_args()
    if args.debug:
        args.loglevel = 'debug'
    logger = setup_logging(args.logfile, args.loglevel, LOGGER_NAME)
    banner_log('create_admin.py')

    # Input Validations
    if (validName(args.username) is False):
        banner_log("Script failed")
        logger.error('username is not valid.')
        return 1

    if (validEmail(args.email) is False):
        banner_log("Script failed")
        logger.error('email is not valid.')
        return 1

    if (validClaimedId(args.claimed_id) is False):
        banner_log("Script failed")
        logger.error('claimed_id is not valid.')
        return 1

    exists = False

    # Verifies if an account with the same email exists
    retval = gsql_exec(
        "SELECT count(*) as count FROM accounts WHERE preferred_email='" +
        args.email + "'")
    count = getColumnValue(retval[1], 'count')
    if not retval[0] == 0:
        return 1

    if int(count) > 0:
        logger.info("An account with email=" + args.email + " already exists.")
        exists = True

    # Verifies if an account with the same name exists
    retval = gsql_exec(
        "SELECT count(*) as count FROM accounts WHERE full_name='" +
        args.username + "'")
    count = getColumnValue(retval[1], 'count')
    if not retval[0] == 0:
        return 1

    if int(count) > 0:
        logger.info("An account with full_name=" + args.username +
                    " already exists.")
        exists = True

    # Just check if the account already exists...
    if args.check_exists:
        banner_log('Script completed')
        return exists

    if exists is True:
        logger.info("Skipping create.")
    else:
        # Generates new account_id
        sql_command = "SELECT max(account_id) as max_account_id from accounts"
        retval = gsql_exec(sql_command)
        new_account_id = int(getColumnValue(retval[1], 'max_account_id')) + 1
        if not retval[0] == 0:
            return 1

        # Inserts the new account
        sql_command = "INSERT INTO accounts (full_name, preferred_email, maximum_page_size, show_site_header, use_flash_clipboard, account_id) VALUES ('" + args.username + "', '" + args.email + "',25,'Y','Y', " + str(
            new_account_id) + ")"
        retval = gsql_exec(sql_command)
        # {"type":"error","message":"Duplicate entry '6' for key 'PRIMARY'"}
        if not retval[0] == 0:
            return 1

        # Inserts the new account_id in the Administrator group
        sql_command = "INSERT INTO account_group_members (account_id, group_id)VALUES (" + str(
            new_account_id) + ",1)"
        retval = gsql_exec(sql_command)
        if not retval[0] == 0:
            return 1

        # Inserts in external accounts
        sql_command = "INSERT INTO `account_external_ids` (account_id, email_address, password, external_id) VALUES (" + str(
            new_account_id
        ) + ",'" + args.email + "',NULL,'" + args.claimed_id + "')"
        retval = gsql_exec(sql_command)
        if not retval[0] == 0:
            return 1

        subprocess.call('puppet agent --test > /dev/null 2>&1 &',
                        shell=True,
                        stdin=None,
                        stdout=None,
                        stderr=None,
                        close_fds=True)

    banner_log('Script completed')
    return 0
示例#6
0
def main():
    global LOGGER_NAME
    # http://docs.python.org/2/library/argparse.html
    parser = argparse.ArgumentParser(description='Creates Gerrit Admin Accounts')
    parser.add_argument('--loglevel', help='Specify the default logging level (optional).', choices=['debug', 'info', 'warning', 'error', 'DEBUG', 'INFO', 'WARNING', 'ERROR'], default='info')
    parser.add_argument('--logfile', help='Specify logfile name.', default='/tmp/create_admin.log')
    parser.add_argument('--debug', help='turn on debug output', action='store_true', default=False)
    parser.add_argument('--working_dir', help='working directory.', default='/tmp')
    parser.add_argument('--username', help='change default user name to create as first account.', default='')
    parser.add_argument('--email', help='specify the email address for the user.', default='')
    parser.add_argument('--claimed_id', help='specify the claimed id, example: https://login.launchpad.net/+id/MJA3AHw', default='')
    # parser.add_argument('--ssh_pubkey', help='pupblic key to use. Example, generate with :\n ssh-keygen -t rsa  -f ~/.ssh/gerrit2 -P ""', default='/home/gerrit2/.ssh/gerrit2.pub')
    parser.add_argument('--check_exists', help='checks if the account exists 0 == exists, 1 == not exists', action='store_true', default=False)
    args = parser.parse_args()
    if args.debug:
        args.loglevel = 'debug'
    logger = setup_logging(args.logfile, args.loglevel, LOGGER_NAME)
    banner_log('create_admin.py')

    # Input Validations
    if (validName(args.username) is False):
        banner_log("Script failed")
        logger.error('username is not valid.')
        return 1

    if (validEmail(args.email) is False):
        banner_log("Script failed")
        logger.error('email is not valid.')
        return 1

    if (validClaimedId(args.claimed_id) is False):
        banner_log("Script failed")
        logger.error('claimed_id is not valid.')
        return 1

    exists = False

    # Verifies if an account with the same email exists
    retval = gsql_exec("SELECT count(*) as count FROM accounts WHERE preferred_email='" + args.email + "'")
    count = getColumnValue(retval[1], 'count')
    if not retval[0] == 0:
        return 1

    if int(count) > 0:
        logger.info("An account with email=" + args.email + " already exists.")
        exists = True

    # Verifies if an account with the same name exists
    retval = gsql_exec("SELECT count(*) as count FROM accounts WHERE full_name='" + args.username + "'")
    count = getColumnValue(retval[1], 'count')
    if not retval[0] == 0:
        return 1

    if int(count) > 0:
        logger.info("An account with full_name=" + args.username + " already exists.")
        exists = True

    # Just check if the account already exists...
    if args.check_exists:
        banner_log('Script completed')
        return exists

    if exists is True:
        logger.info("Skipping create.")
    else:
        # Generates new account_id
        sql_command = "SELECT max(account_id) as max_account_id from accounts"
        retval = gsql_exec(sql_command)
        new_account_id = int(getColumnValue(retval[1], 'max_account_id')) + 1
        if not retval[0] == 0:
            return 1

        # Inserts the new account
        sql_command = "INSERT INTO accounts (full_name, preferred_email, maximum_page_size, show_site_header, use_flash_clipboard, account_id) VALUES ('" + args.username + "', '" + args.email + "',25,'Y','Y', " + str(new_account_id) + ")"
        retval = gsql_exec(sql_command)
        # {"type":"error","message":"Duplicate entry '6' for key 'PRIMARY'"}
        if not retval[0] == 0:
            return 1

        # Inserts the new account_id in the Administrator group
        sql_command = "INSERT INTO account_group_members (account_id, group_id)VALUES (" + str(new_account_id) + ",1)"
        retval = gsql_exec(sql_command)
        if not retval[0] == 0:
            return 1

        # Inserts in external accounts
        sql_command = "INSERT INTO `account_external_ids` (account_id, email_address, password, external_id) VALUES (" + str(new_account_id) + ",'" + args.email + "',NULL,'" + args.claimed_id + "')"
        retval = gsql_exec(sql_command)
        if not retval[0] == 0:
            return 1

        subprocess.call('puppet agent --test > /dev/null 2>&1 &', shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)

    banner_log('Script completed')
    return 0
示例#7
0
def main():
    global LOGGER_NAME
    # http://docs.python.org/2/library/argparse.html
    parser = argparse.ArgumentParser(
        description='run gerrit gsql commands from yaml.')
    parser.add_argument('--loglevel',
                        help='Specify the default logging level (optional).',
                        choices=[
                            'debug', 'info', 'warning', 'error', 'DEBUG',
                            'INFO', 'WARNING', 'ERROR'
                        ],
                        default='info')
    parser.add_argument('--logfile',
                        help='Specify logfile name.',
                        default='/tmp/gerrit_runsql.log')
    parser.add_argument('--loggername',
                        help='Specify a name for the logger.',
                        default=LOGGER_NAME)
    parser.add_argument('--debug',
                        help='turn on debug output',
                        action='store_true',
                        default=False)
    parser.add_argument('--working_dir',
                        help='working directory.',
                        default='/tmp')
    parser.add_argument('--onlyif_not_hasrows',
                        help='only run if the sql does not have rows.',
                        default='')
    parser.add_argument('--check',
                        help='only echo sql we will execute, do not run it',
                        action='store_true',
                        default=False)
    parser.add_argument(
        '--sql_config_file',
        help='change default user name to create as first account.',
        default='/tmp/gerrit_init.sql.yaml')
    args = parser.parse_args()
    if args.debug:
        args.loglevel = 'debug'
    LOGGER_NAME = args.loggername
    logger = setup_logging(args.logfile, args.loglevel, LOGGER_NAME)
    banner_start()
    logger.debug("parsed arguments")

    # check to see that we can connect
    if not gsql_exec('select @@version')[0] == 0:
        banner_end_fail()
        return 1

    retval = [0, '0 rows']
    if args.onlyif_not_hasrows != "":
        retval = gsql_exec(args.onlyif_not_hasrows)
        if not retval[0] == 0:
            logger.error("onlyif_not_hasrows check failed: " + retval[1])
            logger.error("attempted to run sql: " + args.onlyif_not_hasrows)
            banner_end_fail()
            return 1
    else:
        logger.debug("not performing pre-execution check.")

    if not retval[1].upper().rstrip('\n').find('0 ROWS') >= 0:
        logger.info("onlyif_not_hasrows found rows, do nothing.")
        banner_end()
        return 0

    f = open(args.sql_config_file)
    dataMap = yaml.safe_load(f)
    f.close()

    for sql in dataMap['gsql']:
        logger.info("gsql executing : " + sql)
        if not args.check:
            retval = gsql_exec(sql)
            if not retval[0] == 0:
                logger.error("Failed to process gsql: " + retval[1])
                banner_end_fail()
                return 1
        else:
            logger.warn("skipping exec, check is on")
    banner_end()
    return 0