Exporting Ninja Support Logs on Linux Using a Bash Script 

In IT environments, efficient troubleshooting and maintenance are critical for ensuring system reliability. Logs play a pivotal role in diagnosing issues, identifying potential vulnerabilities, and maintaining compliance. For IT professionals and Managed Service Providers (MSPs) using NinjaOne, exporting support logs from Linux systems can be a common task. This blog post provides an in-depth look at a Bash script designed to automate this process.

Understanding the Script’s Purpose and Importance

Log files are vital for monitoring system behavior, diagnosing issues, and maintaining audit trails. NinjaOne’s platform is popular among IT professionals for its remote monitoring and management capabilities, but handling logs across diverse environments like Linux requires reliable tools. This script simplifies the process of exporting NinjaOne support logs to a specified directory, offering both convenience and consistency.

The Script:

#!/usr/bin/env bash

# Description: Exports the Ninja Support Logs to the specified directory for Linux.
# By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
# Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
# Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
# Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
# Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
# Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
# Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
# EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#
# Preset Parameter: --destination "/tmp"
#   The directory to export the logs to.
#
# Preset Parameter: --help
#   Displays some help text.

# These are all our preset parameter defaults. You can set these = to something if you would prefer the script defaults to a certain parameter value.
_arg_destination="/tmp"

# Help text function for when invalid input is encountered
print_help() {
    printf '\n\n%s\n\n' 'Usage: [--destination|-d <arg>] [--help|-h]'
    printf '%s\n' 'Preset Parameter: --destination "/tmp"'
    printf '\t%s\n' "Replace the text encased in quotes with the directory to export the logs to."
    printf '\n%s\n' 'Preset Parameter: --help'
    printf '\t%s\n' "Displays this help menu."
}

# Determines whether or not help text is necessary and routes the output to stderr
die() {
    local _ret="${2:-1}"
    echo "$1" >&2
    test "${_PRINT_HELP:-no}" = yes && print_help >&2
    exit "${_ret}"
}

# Grabbing the parameters and parsing through them.
parse_commandline() {
    while test $# -gt 0; do
        _key="$1"
        case "$_key" in
        --destination | -d)
            test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
            _arg_destination=$2
            shift
            ;;
        --destination=*)
            _arg_destination="${_key##--destination=}"
            ;;
        --help | -h)
            _PRINT_HELP=yes die 0
            ;;
        *)
            _PRINT_HELP=yes die "FATAL ERROR: Got an unexpected argument '$1'" 1
            ;;
        esac
        shift
    done
}

parse_commandline "$@"

# If script form is used override commandline arguments
if [[ -n $destination ]] && [[ "${destination}" != "null" ]]; then
    _arg_destination="$destination"
fi

# Get the path to the NinjaRMMAgent from the environment variable NINJA_DATA_PATH
_data_path=$(printenv | grep -i NINJA_DATA_PATH | awk -F = '{print $2}')
if [[ -z "${_data_path}" ]]; then
    # If the environment variable NINJA_DATA_PATH is not set, try to find the NinjaRMMAgent in the Applications folder
    _data_path="/opt/NinjaRMMAgent/programdata"
    if [[ -z "${_data_path}" ]]; then
        echo "[Error] No NinjaRMMAgent found. Please make sure you have the NinjaRMMAgent installed and that it is running."
        exit 1
    fi
fi

# Get the current date
cur_date="$(date +%Y-%m-%d)"

# Trim the trailing slash from the destination path
dest_path=$(echo "$_arg_destination" | sed 's/\/$//')

# Collect the logs from the following directories
if [ "$(command -v zip)" ]; then
    echo "[Info] Exporting logs to $dest_path/NinjaSupportLogs.zip"
    if zip -r -q "$dest_path/$cur_date-NinjaLogs.zip" "$_data_path/logs" "$_data_path/policy" "$_data_path/jsonoutput" "$_data_path/jsoninput" "$_data_path/patch"; then
        echo "[Info] Logs exported to $dest_path/$cur_date-NinjaLogs.zip"
    else
        echo "[Error] Failed to export logs to $dest_path/$cur_date-NinjaLogs.zip"
        exit 1
    fi
elif [ "$(command -v tar)" ]; then
    echo "[Warn] zip command not found. Using tar instead."
    echo "[Info] Exporting logs to $dest_path/NinjaSupportLogs.tar.gz"
    if tar -czf "$dest_path/$cur_date-NinjaLogs.tar.gz" "$_data_path/logs" "$_data_path/policy" "$_data_path/jsonoutput" "$_data_path/jsoninput" "$_data_path/patch"; then
        echo "[Info] Logs exported to $dest_path/$cur_date-NinjaLogs.tar.gz"
    else
        echo "[Error] Failed to export logs to $dest_path/$cur_date-NinjaLogs.tar.gz"
        exit 1
    fi
else
    echo "[Error] zip or tar not found. Please install zip or tar."
    exit 1
fi

 

Save time with over 300+ scripts from the NinjaOne Dojo.

Get access today.

Detailed Breakdown of the Script

Preset Parameters and Initial Setup

The script begins with two main preset parameters:

  • –destination (-d): Specifies the directory where logs will be exported, defaulting to /tmp.
  • –help (-h): Provides a detailed help menu for script usage.

These parameters ensure users can easily configure the script for their specific needs or troubleshoot issues when required.

Command-Line Parsing

The parse_commandline function processes user inputs, validating them to ensure correct usage. If invalid or unexpected arguments are encountered, the script gracefully exits, displaying relevant help text.

Environment Variable Detection

To locate the NinjaOne agent’s data path, the script first checks the environment variable NINJA_DATA_PATH. If this is not set, it defaults to a common installation path (/opt/NinjaRMMAgent/programdata). This fallback mechanism ensures compatibility across different environments.

Log Collection and Export

The script:

  • Determines the current date to timestamp the exported logs.
  • Trims trailing slashes from the destination path for consistency.
  • Collects logs from directories such as logs, policy, jsonoutput, jsoninput, and patch.

Based on the system’s available tools, the logs are archived using either zip or tar. This dual approach ensures compatibility with various Linux distributions, prioritizing zip but falling back to tar if necessary.

Error Handling

Robust error-handling mechanisms are built in to:

  • Alert users if the NinjaOne agent is not found or running.
  • Warn about missing utilities (zip or tar).
  • Notify users of any failures during the log export process.

Hypothetical Use Case

Scenario: An MSP managing multiple Linux servers notices inconsistent application behavior on one server monitored via NinjaOne. The technician uses the script to export support logs for analysis:

  1. They run the script with the –destination /path/to/logs parameter to store logs in a custom directory.
  2. The script archives logs into a single file, timestamped for traceability.
  3. The technician reviews the exported logs to identify a configuration issue causing the application behavior.

This efficient workflow minimizes downtime and ensures a quick resolution.

Comparisons to Other Methods

Without this script, IT professionals might manually locate and copy log files, leading to inefficiencies and potential errors. While some GUI-based tools offer similar functionality, they often lack the flexibility and automation provided by a script. For Linux environments, this Bash script stands out for its simplicity, reliability, and adaptability.

Frequently Asked Questions

  1. Can this script run on any Linux distribution?
    Yes, provided the system has bash, zip, or tar installed.
  2. What happens if the specified directory doesn’t exist?
    The script will fail to write logs and notify the user. Ensure the destination directory exists before running the script.
  3. How do I verify the NinjaOne agent is running?
    Check the agent’s status using system commands like ps or verify its installation directory for active logs.
  4. What if I need logs from additional directories?
    Modify the script’s zip or tar commands to include additional paths.

Implications of Using the Script

Exported logs can contain sensitive information. Mishandling these files could result in data exposure or compliance issues. IT teams should secure exported log files using appropriate permissions and encryption where necessary.

From a broader perspective, this script promotes proactive IT management, enabling quicker diagnostics and strengthening overall system reliability.

Best Practices for Using the Script

  • Run the script as a user with sufficient permissions to access the NinjaOne data directory.
  • Regularly update the script to accommodate changes in directory structures or tool requirements.
  • Store exported logs in a secure location and restrict access to authorized personnel.
  • Validate the presence of required utilities (zip or tar) before deploying the script.

Final Thoughts

Automating the export of NinjaOne support logs on Linux enhances efficiency and consistency for IT professionals and MSPs. This script offers a straightforward yet powerful solution to a routine challenge. By leveraging tools like this, IT teams can focus more on proactive management rather than manual tasks.

NinjaOne continues to empower IT professionals with tools that streamline operations and improve system visibility. Whether through this script or its broader suite of solutions, NinjaOne remains an invaluable ally in maintaining robust IT environments.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).