Exemplo n.º 1
0
def symlink_dir(directory):
    """Get directory in which the symlinked files are located.

    Args:
        directory: Directory with the symlinks

    Returns:
        result: Directory to which the files have symlinks

    """
    # Initialize key variables
    data_dictionary = {}
    result = None
    # Get all the filenames in the directory
    filenames = _filepaths(directory)

    # Get the name of the directory to which the files are symlinked
    for filename in filenames:
        if os.path.islink(filename) is False:
            continue
        if '/etc/systemd/system/multi-user.target.wants' not in filename:
            continue
        data_dictionary[Path(filename).resolve().absolute()] = True

    # Get the first directory in the dictionary
    for key in sorted(data_dictionary.keys()):
        if '/lib/' not in str(key):
            continue
        result = os.path.dirname(str(key))
        break
    # Die if there are no symlinks
    if bool(result) is False:
        shared.log(
            'No symlinks found in the directory: "{}"'.format(directory))
    return result
Exemplo n.º 2
0
def create_user(user_name, directory, shell, verbose):
    """Create user and their respective group.

    Args:
        user_name: The name and group of the user being created
        directory: The home directory of the user
        shell: The shell of the user
        verbose: A boolean value that a allows the script to run in verbose
        mode

    Returns:
        None
    """
    # Ensure user has sudo privileges
    if getpass.getuser() == 'root':

        # If the group specified does not exist, it gets created
        if not group_exists(user_name):
            shared.run_script('groupadd {0}'.format(user_name), verbose)

        # If the user specified does not exist, they get created
        if not user_exists(user_name):
            shared.run_script(
                'useradd -d {1} -s {2} -g {0} {0}'.format(
                    user_name, directory, shell), verbose)
    else:
        # Die if not root
        shared.log('You are currently not running the script as root')
Exemplo n.º 3
0
def _get_runtime_directory(config_directory):
    """Get the RuntimeDirectory.

    Args:
        config_dir: Configuration directory

    Returns:
        tuple: (Path, Relative Path to /var/run)

    """
    result = None
    filepath = os.path.join(config_directory, 'pattoo.yaml')
    if os.path.isfile(filepath) is False:
        shared.log('{} does not exist'.format(filepath))
    # Read yaml file
    try:
        file_handle = open(filepath, 'r')
    except PermissionError:
        log.log2die_safe(1080, '''\
Insufficient permissions for reading the file: {}.''')
    else:
        with file_handle:
            yaml_from_file = file_handle.read()
    config = yaml.safe_load(yaml_from_file)

    pattoo = config.get('pattoo')
    if bool(pattoo) is True:
        result = pattoo.get('system_daemon_directory')
    if result is None:
        shared.log('''\
"system_daemon_directory" parameter not found in the {} configuration file\
'''.format(filepath))
    _result = result.replace('/var/run/', '')
    _result = _result.replace('/run/', '')
    return (result, _result)
Exemplo n.º 4
0
def _check_symlinks(etc_dir, daemons):
    """Ensure the files in the etc dir are symlinks.

    Args:
        etc_dir: The directory that the symlinks are located in
        symlink_dir: The directory that the symlinks point to
        daemons: The list of system daemons

    Returns:
        None

    """
    for daemon in daemons:
        # Initialize key variables
        symlink_path = os.path.join(etc_dir, daemon)

        # Say what we are doing
        print('Checking if the {}.service file is a symlink '.format(daemon))
        link = os.path.islink('{0}.service'.format(symlink_path))
        if link is False:
            if getpass.getuser() != 'root':
                shared.log('Current user is not root')
            print('Creating symlink for {}'.format(daemon))
            # Create symlink if it doesn't exist
            shared.run_script('systemctl enable {}'.format(daemon))
Exemplo n.º 5
0
def preflight(config_dir, etc_dir):
    """Make sure the environment is OK.

    Args:
        config_dir: Location of the configuratiion directory
        etc_dir: Location of the systemd files

    Returns:
        None

    """
    # Make sure config_dir exists
    if os.path.isdir(config_dir) is False:
        shared.log('''\
Expected configuration directory "{}" does not exist.'''.format(config_dir))

    # Verify whether the script is being run by root or sudo user
    if bool(os.getuid()) is True:
        shared.log('''\
This script must be run as the "root" user or with "sudo" privileges''')

    # Check to see whether this is a systemd system
    try:
        check_output(['pidof', 'systemd'])
    except:
        shared.log('This is not a "systemd" system. This script should not be run.')

    # Check existence of /etc/systemd/system/multi-user.target.wants directory
    if os.path.isdir(etc_dir) is False:
        shared.log('Expected systemd directory "{}" does not exist.'.format(etc_dir))
def check_user():
    """Validate conditions needed to start installation.

    Prevents installation if the script is not run as root

    Args:
        None

    Returns:
        True: If conditions for installation are satisfied

    """
    if getpass.getuser() != 'travis':
        if getpass.getuser() != 'root':
            shared.log('You are currently not running the script as root.\
Run as root to continue')
    return True
def install_dependencies():
    """Install the necessary system dependencies for the snmp agent.

    Args:
        None

    Returns:
        None
    """
    # Initialize key variables
    distribution = distro.id()

    if distribution == 'debian' or distribution == 'ubuntu':
        # Say what we are doing
        print('Installing easy snmp dependencies...')

        # Install net-snmp with package manager
        shared.run_script(
            'sudo apt-get install libsnmp-dev snmp-mibs-downloader')

        # Install easy snmp dependencies
        shared.run_script('sudo apt-get install gcc python-dev')

    elif distribution == 'rhel' or distribution == 'centos':
        # Install net-snmp with package manager
        shared.run_script('sudo yum install net-snmp-devel')

        # Install easy snmp dependencies
        shared.run_script('sudo yum install gcc python-devel')

    # Die if distribution isn't debian or rhel based
    else:
        shared.log('''\
Your operating system does not support Net-SNMP 5.7.x \n \
Please follow this guide to build and install Net-SNMP 5.7.x on your system \
        http://www.net-snmp.org/docs/INSTALL.html''')
 def test_log(self):
     """Unittest to test the _log function."""
     with self.assertRaises(SystemExit) as cm_:
         shared.log("Test Error Message")
     self.assertEqual(cm_.exception.code, 3)
Exemplo n.º 9
0
def install(requirements_dir, installation_directory, verbose=False):
    """Ensure PIP3 packages are installed correctly.

    Args:
        requirements_dir: The directory with the pip_requirements file.
        installation_directory: Directory where packages must be installed.
        verbose: Print status messages if True

    Returns:
        True if pip3 packages are installed successfully

    """
    # Initialize key variables
    lines = []

    # Read pip_requirements file
    filepath = '{}{}pip_requirements.txt'.format(requirements_dir, os.sep)

    # Say what we are doing
    print('Checking pip3 packages')
    if os.path.isfile(filepath) is False:
        shared.log('Cannot find PIP3 requirements file {}'.format(filepath))

    # Opens pip_requirements file for reading
    try:
        _fp = open(filepath, 'r')
    except PermissionError:
        log.log2die_safe(1079, '''\
Insufficient permissions for reading the file: {}. \
Ensure the file has read-write permissions and try again'''.format(filepath))
    else:
        line = _fp.readline()
        while line:
            # Strip line
            _line = line.strip()
            # Read line
            if True in [_line.startswith('#'), bool(_line) is False]:
                pass
            else:
                lines.append(_line)
            line = _fp.readline()

    # Process each line of the file
    for line in lines:
        # Determine the package
        package = line.split('=', 1)[0]
        package = package.split('>', 1)[0]

        # If verbose is true, the package being checked is shown
        if verbose:
            print('Installing package {}'.format(package))
        command = 'python3 -m pip show {}'.format(package)
        (returncode, _, _) = shared.run_script(
            command, verbose=verbose, die=False)

        # Install any missing pip3 package
        if bool(returncode) is True:
            install_missing_pip3(package, verbose=verbose)

    # Set ownership of any newly installed python packages to pattoo user
    if getpass.getuser() == 'root':
        if os.path.isdir(installation_directory) is True:
            shared.run_script('chown -R pattoo:pattoo {}'.format(
                installation_directory), verbose=verbose)

    print('pip3 packages successfully installed')