Exporting Ninja Log Files on macOS with a Bash Script

Efficient log management is critical for IT professionals and managed service providers (MSPs). Whether troubleshooting issues or ensuring compliance, having access to relevant logs can be a lifesaver. The provided Bash script streamlines the process of exporting Ninja log files on macOS, making it a valuable tool for IT environments. This post breaks down the script, its use cases, and best practices for deploying it.

Background on Ninja Log Management

NinjaOne is a comprehensive IT management solution, and its agents generate logs that can provide crucial insights into system performance, policies, and configurations. For macOS users, manually locating and exporting these logs can be tedious. This script automates the process, ensuring that logs are exported to a specified directory in a consistent format.

IT professionals and MSPs frequently need these logs for diagnostics, audits, or compliance purposes. By automating log exports, the script reduces manual effort and minimizes the risk of human error.

The Script

#!/usr/bin/env bash

# Description: Exports the Ninja Support Logs to the specified directory for Mac.
#   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 "/private/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="/private/tmp"

# Help text function for when invalid input is encountered
print_help() {
    printf '\n\n%s\n\n' 'Usage: [--destination|-d <arg>] [--createPath|-c] [--help|-h]'
    printf '%s\n' 'Preset Parameter: --destination "/private/tmp/ninjaLogs" --createPath'
    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=}"
            ;;
        --createPath | -c)
            _arg_createPath="true"
            ;;
        --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
if [[ -n $createPath ]] && [[ "${createPath}" == "true" ]]; then
    _arg_createPath="true"
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="/Applications/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 and remove any duplicate slashes from the destination path
dest_path=$(echo "$_arg_destination" | sed 's/\/$//' | sed 's/\/\+/\//g')

if [ -e "${dest_path}" ]; then
    echo "[Info] The destination path (${dest_path}) exists."
else
    echo "[Warn] The destination path (${dest_path}) does not exist."
    if [[ "${_arg_createPath}" == "true" ]]; then
        echo "[Info] Creating the destination path (${dest_path})"
        mkdir -p "${dest_path}"
    else
        echo "[Error] The destination path (${dest_path}) does not exist."
        exit 1
    fi
fi

echo "[Info] Exporting logs to $dest_path/NinjaSupportLogs.zip"

# Collect the logs from the following directories
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

 

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

Get access today.

Step-by-Step Breakdown of the Script

Overview of Parameters

The script begins by defining and parsing user-provided parameters:

  • –destination or -d: Specifies the directory where logs will be exported. Defaults to /private/tmp.
  • –createPath or -c: Indicates whether to create the destination directory if it doesn’t exist.
  • –help or -h: Displays usage instructions.

Help Functionality

The print_help function provides guidance for users unfamiliar with the script’s parameters. It details the purpose of each flag, ensuring clarity.

Parsing Command-Line Arguments

The parse_commandline function processes the input arguments. It validates required inputs, checks for unexpected arguments, and assigns values to the script’s variables.

Resolving the Ninja Data Path

The script identifies the location of Ninja logs using:

  1. The NINJA_DATA_PATH environment variable, if set.
  2. A default fallback to /Applications/NinjaRMMAgent/programdata.

If neither path is available, the script exits with an error, ensuring users are informed about the missing NinjaOne agent.

Preparing the Destination Directory

The script cleans and validates the destination path. If the directory doesn’t exist:

  • It creates the directory if the –createPath flag is set.
  • Otherwise, it exits with an error.

Exporting Logs

Using the zip utility, the script collects logs from predefined Ninja directories (logs, policy, jsonoutput, jsoninput, patch) and compresses them into a timestamped ZIP file. This ensures easy retrieval and organization of exported logs.

Potential Use Cases

Hypothetical Scenario: Resolving Endpoint Performance Issues

Imagine an MSP managing multiple endpoints using NinjaOne. A client reports slow performance on a macOS device. Instead of manually sifting through logs, the IT technician runs this script:

  • Exports logs to a predefined directory.
  • Reviews the compressed logs for patterns or errors.
  • Pinpoints the root cause, such as policy misconfiguration or patching issues.

The automation provided by the script saves time and ensures accurate diagnostics.

Comparisons to Alternative Methods

Manual log export involves navigating directories, selecting relevant files, and compressing them. This approach is prone to errors and is time-consuming.

Using the NinjaOne web interface for log retrieval is another option, but it may lack flexibility or automation capabilities on macOS. The script’s command-line approach offers precision and repeatability, making it ideal for IT professionals comfortable with scripting.

FAQs

What happens if the destination directory doesn’t exist?
The script can create the directory if the –createPath flag is used. Otherwise, it exits with an error.

Can this script run on Linux or Windows?
While designed for macOS, it could be adapted for Linux. Windows would require a different script or approach due to system differences.

What logs are included in the ZIP file?
The script collects logs from directories such as logs, policy, jsonoutput, jsoninput, and patch.

Implications for IT Security

Exported logs contain sensitive information, such as configurations and system states. Mishandling these files could expose vulnerabilities. IT teams should enforce strict access controls and encrypt exported logs when storing or transmitting them.

By automating log exports, the script also reduces the time windows in which logs might be inaccessible during incidents, bolstering operational resilience.

Recommendations for Using the Script

  1. Run in a Secure Environment: Ensure only authorized personnel have access to the script and exported logs.
  2. Test in Non-Production Systems: Validate the script on non-critical systems before deploying it widely.
  3. Schedule Regular Exports: Integrate the script with a task scheduler like cron for periodic log exports.

Final Thoughts

The ability to export Ninja log files on macOS efficiently is a significant advantage for IT professionals and MSPs. This Bash script not only simplifies the process but also ensures consistency and accuracy. NinjaOne users can leverage such automation to enhance their troubleshooting and compliance efforts, further underscoring the platform’s value in IT management.

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).