Foreground Application Monitoring on macOS
Monitor and manage foreground applications across your MacFleet devices using advanced AppleScript and system monitoring tools. This tutorial covers application tracking, productivity analysis, security monitoring, and enterprise application lifecycle management.
Understanding macOS Application Monitoring
macOS provides several methods for application monitoring and management:
- AppleScript - Automation language for application control and monitoring
- System Events - System-level process and application information
- Activity Monitor - Real-time application and resource monitoring
- Finder Integration - Application visibility and state management
Basic Foreground Application Detection
Simple Application List
#!/bin/bash
# Basic script to fetch foreground applications
osascript <<EOF
tell application "Finder"
set visibleProcesses to name of every process whose visible is true
return visibleProcesses
end tell
EOF
echo "Foreground applications retrieved successfully"
Enhanced Application Information
#!/bin/bash
# Enhanced foreground application monitoring with detailed information
get_foreground_applications() {
osascript <<EOF
tell application "System Events"
set foregroundApps to {}
set visibleProcesses to every process whose visible is true
repeat with aProcess in visibleProcesses
set appName to name of aProcess
set appPID to unix id of aProcess
try
set appPath to POSIX path of (file of aProcess as alias)
on error
set appPath to "N/A"
end try
set appInfo to appName & "|" & appPID & "|" & appPath
set foregroundApps to foregroundApps & {appInfo}
end repeat
return foregroundApps
end tell
EOF
}
# Execute and format output
echo "=== Foreground Applications ==="
get_foreground_applications | tr ',' '\n' | while read -r app_info; do
if [[ -n "$app_info" ]]; then
IFS='|' read -r name pid path <<< "$app_info"
echo "Application: $name"
echo " PID: $pid"
echo " Path: $path"
echo ""
fi
done
Application Monitoring Categories
Application Type Classifications
#!/bin/bash
# Enterprise application categories for monitoring and policy enforcement
declare -A APPLICATION_CATEGORIES=(
["productivity_apps"]="Office suites, document editors, project management tools"
["development_tools"]="IDEs, code editors, development environments, version control"
["communication_apps"]="Email clients, messaging, video conferencing, collaboration"
["creative_software"]="Design tools, media editing, creative applications"
["browser_applications"]="Web browsers, internet-based applications"
["system_utilities"]="System tools, maintenance applications, security software"
["entertainment_media"]="Games, streaming, social media, entertainment platforms"
["financial_software"]="Accounting, finance, banking, payment applications"
["security_tools"]="Antivirus, VPN, security monitoring, encryption tools"
["unauthorized_apps"]="Non-approved, potentially harmful, or restricted applications"
)
# Application risk levels
declare -A RISK_LEVELS=(
["productivity_apps"]="low"
["development_tools"]="medium"
["communication_apps"]="low"
["creative_software"]="medium"
["browser_applications"]="medium"
["system_utilities"]="high"
["entertainment_media"]="high"
["financial_software"]="medium"
["security_tools"]="low"
["unauthorized_apps"]="critical"
)
# Business impact classifications
declare -A BUSINESS_IMPACT=(
["productivity_apps"]="high_positive"
["development_tools"]="high_positive"
["communication_apps"]="high_positive"
["creative_software"]="medium_positive"
["browser_applications"]="medium_neutral"
["system_utilities"]="medium_positive"
["entertainment_media"]="high_negative"
["financial_software"]="high_positive"
["security_tools"]="high_positive"
["unauthorized_apps"]="high_negative"
)
print_application_categories() {
echo "=== Application Monitoring Categories ==="
for category in "${!APPLICATION_CATEGORIES[@]}"; do
echo "Category: $category"
echo " Description: ${APPLICATION_CATEGORIES[$category]}"
echo " Risk Level: ${RISK_LEVELS[$category]}"
echo " Business Impact: ${BUSINESS_IMPACT[$category]}"
echo ""
done
}
# Display available categories
print_application_categories
Application Monitoring Policies
Monitoring Policy Engine
#!/bin/bash
# Monitoring policies for different organizational requirements
declare -A MONITORING_POLICIES=(
["strict_compliance"]="Comprehensive monitoring with real-time alerts and detailed logging"
["productivity_focused"]="Focus on productivity metrics and time tracking"
["security_priority"]="Emphasis on security threats and unauthorized application detection"
["development_optimized"]="Optimized for software development teams and technical workflows"
["creative_workflow"]="Tailored for creative teams and design-focused environments"
["executive_monitoring"]="High-level monitoring for executive and leadership teams"
["guest_restricted"]="Limited monitoring for guest and temporary access accounts"
)
# Policy configurations
get_monitoring_policy() {
local policy_type="$1"
case "$policy_type" in
"strict_compliance")
cat << EOF
{
"monitoring_frequency": "continuous",
"data_retention": "365_days",
"alert_threshold": "immediate",
"logging_level": "comprehensive",
"screenshot_capture": true,
"productivity_tracking": true,
"security_scanning": true,
"compliance_reporting": ["sox", "hipaa", "gdpr", "pci_dss"],
"real_time_alerts": true,
"application_blocking": true,
"time_restrictions": true,
"approval_workflow": true
}
EOF
;;
"productivity_focused")
cat << EOF
{
"monitoring_frequency": "5_minutes",
"data_retention": "90_days",
"alert_threshold": "moderate",
"logging_level": "productivity_metrics",
"screenshot_capture": false,
"productivity_tracking": true,
"security_scanning": false,
"compliance_reporting": ["time_tracking"],
"real_time_alerts": false,
"application_blocking": false,
"time_restrictions": false,
"approval_workflow": false,
"focus_metrics": ["active_time", "app_usage", "productivity_score"]
}
EOF
;;
"security_priority")
cat << EOF
{
"monitoring_frequency": "continuous",
"data_retention": "180_days",
"alert_threshold": "high",
"logging_level": "security_focused",
"screenshot_capture": true,
"productivity_tracking": false,
"security_scanning": true,
"compliance_reporting": ["security_incidents"],
"real_time_alerts": true,
"application_blocking": true,
"time_restrictions": true,
"approval_workflow": true,
"threat_detection": ["malware", "unauthorized_apps", "data_exfiltration"],
"behavioral_analysis": true
}
EOF
;;
*)
echo "Unknown monitoring policy: $policy_type"
return 1
;;
esac
}
# Apply monitoring policy
apply_monitoring_policy() {
local policy="$1"
local config_file="/tmp/monitoring_policy.json"
echo "Applying monitoring policy: $policy"
get_monitoring_policy "$policy" > "$config_file"
if [[ ! -f "$config_file" ]]; then
echo "❌ Failed to generate policy configuration"
return 1
fi
echo "✅ Monitoring policy applied successfully"
echo "Configuration: $config_file"
# Display key policy settings
echo "=== Policy Summary ==="
echo "Monitoring Frequency: $(jq -r '.monitoring_frequency' "$config_file")"
echo "Data Retention: $(jq -r '.data_retention' "$config_file")"
echo "Alert Threshold: $(jq -r '.alert_threshold' "$config_file")"
echo "Real-time Alerts: $(jq -r '.real_time_alerts' "$config_file")"
echo "Application Blocking: $(jq -r '.application_blocking' "$config_file")"
return 0
}
Enterprise Deployment Profiles
Deployment Configuration Templates
#!/bin/bash
# Enterprise deployment profiles for different organizational scenarios
declare -A DEPLOYMENT_PROFILES=(
["corporate_standard"]="Standard corporate deployment with balanced monitoring and productivity"
["high_security_finance"]="High-security monitoring for financial and sensitive departments"
["creative_agency"]="Optimized for creative teams with design and media applications"
["software_development"]="Development-focused monitoring for engineering teams"
["call_center_support"]="Customer service and support team monitoring"
["executive_leadership"]="Executive-level monitoring with privacy considerations"
["remote_workforce"]="Remote worker monitoring with productivity focus"
["guest_contractor"]="Limited monitoring for external contractors and guests"
)
# Profile-specific configurations
get_deployment_config() {
local profile="$1"
case "$profile" in
"corporate_standard")
cat << EOF
{
"monitoring_policy": "productivity_focused",
"application_categories": ["productivity_apps", "communication_apps", "browser_applications"],
"restricted_categories": ["entertainment_media"],
"monitoring_schedule": "business_hours",
"productivity_metrics": {
"enabled": true,
"daily_reports": true,
"weekly_summaries": true,
"goal_tracking": true
},
"security_settings": {
"threat_detection": "standard",
"unauthorized_app_blocking": true,
"malware_scanning": true
},
"privacy_settings": {
"screenshot_frequency": "hourly",
"keystroke_logging": false,
"personal_app_privacy": true
},
"compliance": {
"data_retention": "90_days",
"audit_logging": true,
"reporting_frequency": "weekly"
}
}
EOF
;;
"high_security_finance")
cat << EOF
{
"monitoring_policy": "strict_compliance",
"application_categories": ["productivity_apps", "financial_software", "communication_apps"],
"restricted_categories": ["entertainment_media", "unauthorized_apps"],
"monitoring_schedule": "24_7",
"productivity_metrics": {
"enabled": true,
"real_time_tracking": true,
"detailed_analytics": true,
"compliance_scoring": true
},
"security_settings": {
"threat_detection": "advanced",
"unauthorized_app_blocking": true,
"malware_scanning": true,
"data_loss_prevention": true,
"encryption_verification": true
},
"privacy_settings": {
"screenshot_frequency": "continuous",
"keystroke_logging": true,
"personal_app_privacy": false,
"session_recording": true
},
"compliance": {
"data_retention": "2555_days",
"audit_logging": true,
"reporting_frequency": "daily",
"frameworks": ["sox", "pci_dss", "nist"]
}
}
EOF
;;
"creative_agency")
cat << EOF
{
"monitoring_policy": "productivity_focused",
"application_categories": ["creative_software", "productivity_apps", "communication_apps", "browser_applications"],
"restricted_categories": ["unauthorized_apps"],
"monitoring_schedule": "flexible_hours",
"productivity_metrics": {
"enabled": true,
"creative_workflow_tracking": true,
"project_time_allocation": true,
"inspiration_time_allowance": true
},
"security_settings": {
"threat_detection": "standard",
"unauthorized_app_blocking": false,
"malware_scanning": true,
"creative_software_licensing": true
},
"privacy_settings": {
"screenshot_frequency": "never",
"keystroke_logging": false,
"personal_app_privacy": true,
"creative_process_privacy": true
},
"compliance": {
"data_retention": "60_days",
"audit_logging": false,
"reporting_frequency": "monthly",
"client_confidentiality": true
}
}
EOF
;;
*)
echo "Unknown deployment profile: $profile"
return 1
;;
esac
}
# Deploy profile configuration
deploy_monitoring_profile() {
local profile="$1"
local config_file="/tmp/deployment_config_${profile}.json"
echo "Deploying monitoring profile: $profile"
get_deployment_config "$profile" > "$config_file"
if [[ ! -f "$config_file" ]]; then
echo "❌ Failed to generate deployment configuration"
return 1
fi
echo "✅ Deployment profile ready"
echo "Configuration saved to: $config_file"
# Display profile summary
echo "=== Profile Summary ==="
echo "Monitoring Policy: $(jq -r '.monitoring_policy' "$config_file")"
echo "Monitoring Schedule: $(jq -r '.monitoring_schedule' "$config_file")"
echo "Security Level: $(jq -r '.security_settings.threat_detection' "$config_file")"
echo "Privacy Mode: $(jq -r '.privacy_settings.personal_app_privacy' "$config_file")"
echo "Data Retention: $(jq -r '.compliance.data_retention' "$config_file")"
return 0
}
Enterprise Application Management System
#!/bin/bash
# MacFleet Enterprise Application Monitoring System
# Comprehensive foreground application monitoring and management
# Configuration
CONFIG_DIR="/etc/macfleet/application_monitoring"
LOG_FILE="/var/log/macfleet_app_monitoring.log"
DATA_DIR="/var/data/macfleet/applications"
REPORTS_DIR="/var/reports/macfleet/applications"
AUDIT_LOG="/var/log/macfleet_app_audit.log"
ALERTS_DIR="/var/alerts/macfleet/applications"
# Create required directories
create_directories() {
local directories=("$CONFIG_DIR" "$DATA_DIR" "$REPORTS_DIR" "$ALERTS_DIR")
for dir in "${directories[@]}"; do
if [[ ! -d "$dir" ]]; then
sudo mkdir -p "$dir"
sudo chmod 755 "$dir"
fi
done
}
# Logging functions
log_action() {
echo "$(date '+%Y-%m-%d %H:%M:%S') [INFO] $1" | tee -a "$LOG_FILE"
}
log_error() {
echo "$(date '+%Y-%m-%d %H:%M:%S') [ERROR] $1" | tee -a "$LOG_FILE" >&2
}
audit_log() {
echo "$(date '+%Y-%m-%d %H:%M:%S') [AUDIT] $1" | tee -a "$AUDIT_LOG"
}
# Application database management
initialize_app_database() {
local db_file="$DATA_DIR/application_database.json"
if [[ ! -f "$db_file" ]]; then
cat > "$db_file" << EOF
{
"version": "1.0",
"created": "$(date -Iseconds)",
"applications": {},
"monitoring_sessions": {},
"productivity_metrics": {},
"security_events": {}
}
EOF
log_action "Application database initialized: $db_file"
fi
}
# Advanced application detection
get_comprehensive_app_info() {
local output_file="$1"
local timestamp="$(date -Iseconds)"
# Get foreground applications with detailed information
osascript <<EOF > "$output_file"
tell application "System Events"
set appList to {}
set visibleProcesses to every process whose visible is true
repeat with aProcess in visibleProcesses
try
set appName to name of aProcess
set appPID to unix id of aProcess
set appMemory to ""
set appCPU to ""
set appPath to ""
set appBundle to ""
set appVersion to ""
try
set appPath to POSIX path of (file of aProcess as alias)
end try
try
tell application "Finder"
set appFile to POSIX file appPath as alias
set appBundle to id of (info for appFile)
set appVersion to version of (info for appFile)
end tell
end try
set appInfo to "{"
set appInfo to appInfo & "\\"name\\": \\"" & appName & "\\", "
set appInfo to appInfo & "\\"pid\\": " & appPID & ", "
set appInfo to appInfo & "\\"path\\": \\"" & appPath & "\\", "
set appInfo to appInfo & "\\"bundle_id\\": \\"" & appBundle & "\\", "
set appInfo to appInfo & "\\"version\\": \\"" & appVersion & "\\", "
set appInfo to appInfo & "\\"timestamp\\": \\"$timestamp\\""
set appInfo to appInfo & "}"
set appList to appList & {appInfo}
end try
end repeat
set AppleScript's text item delimiters to ","
set result to "[" & (appList as string) & "]"
set AppleScript's text item delimiters to ""
return result
end tell
EOF
}
# Application categorization and risk assessment
categorize_application() {
local app_name="$1"
local app_path="$2"
local app_bundle="$3"
# Application categorization logic
case "$app_name" in
*"Safari"*|*"Chrome"*|*"Firefox"*|*"Edge"*)
echo "browser_applications"
;;
*"Office"*|*"Word"*|*"Excel"*|*"PowerPoint"*|*"Pages"*|*"Numbers"*|*"Keynote"*)
echo "productivity_apps"
;;
*"Xcode"*|*"Visual Studio"*|*"IntelliJ"*|*"Eclipse"*|*"Sublime"*|*"Atom"*)
echo "development_tools"
;;
*"Photoshop"*|*"Illustrator"*|*"Final Cut"*|*"Logic"*|*"Sketch"*|*"Figma"*)
echo "creative_software"
;;
*"Slack"*|*"Teams"*|*"Zoom"*|*"Skype"*|*"Mail"*|*"Messages"*)
echo "communication_apps"
;;
*"iTunes"*|*"Spotify"*|*"Netflix"*|*"YouTube"*|*"Game"*|*"Steam"*)
echo "entertainment_media"
;;
*"Finder"*|*"Terminal"*|*"Activity Monitor"*|*"System Preferences"*)
echo "system_utilities"
;;
*)
# Check bundle ID for better categorization
case "$app_bundle" in
com.apple.*)
echo "system_utilities"
;;
com.microsoft.*)
echo "productivity_apps"
;;
com.adobe.*)
echo "creative_software"
;;
*)
echo "unknown_application"
;;
esac
;;
esac
}
# Security threat detection
detect_security_threats() {
local app_data="$1"
local threats_file="$ALERTS_DIR/security_threats_$(date +%Y%m%d_%H%M%S).json"
echo "=== Security Threat Detection ==="
echo "Scanning applications for security threats..."
# Known malicious application patterns
local malicious_patterns=(
"keylogger"
"spyware"
"adware"
"trojan"
"backdoor"
"cryptominer"
"ransomware"
)
# Unauthorized application detection
local unauthorized_apps=()
local suspicious_apps=()
# Parse application data and check for threats
while IFS= read -r app_line; do
if [[ -n "$app_line" ]]; then
local app_name=$(echo "$app_line" | jq -r '.name' 2>/dev/null)
local app_path=$(echo "$app_line" | jq -r '.path' 2>/dev/null)
# Check against malicious patterns
for pattern in "${malicious_patterns[@]}"; do
if [[ "$app_name" =~ $pattern ]] || [[ "$app_path" =~ $pattern ]]; then
suspicious_apps+=("$app_name:$pattern")
audit_log "Suspicious application detected: $app_name (pattern: $pattern)"
fi
done
# Check for applications in unauthorized locations
if [[ "$app_path" =~ /tmp/ ]] || [[ "$app_path" =~ /var/tmp/ ]] || [[ "$app_path" =~ /Downloads/ ]]; then
unauthorized_apps+=("$app_name:$app_path")
audit_log "Unauthorized location application: $app_name (path: $app_path)"
fi
fi
done <<< "$(echo "$app_data" | jq -c '.[]' 2>/dev/null)"
# Generate threat report
local threat_report=$(cat << EOF
{
"scan_timestamp": "$(date -Iseconds)",
"hostname": "$(hostname)",
"suspicious_applications": $(printf '%s\n' "${suspicious_apps[@]}" | jq -R . | jq -s .),
"unauthorized_applications": $(printf '%s\n' "${unauthorized_apps[@]}" | jq -R . | jq -s .),
"threat_level": "$([ ${#suspicious_apps[@]} -gt 0 ] && echo "high" || echo "low")",
"recommendations": {
"immediate_action": $([ ${#suspicious_apps[@]} -gt 0 ] && echo "true" || echo "false"),
"quarantine_required": $([ ${#suspicious_apps[@]} -gt 2 ] && echo "true" || echo "false"),
"security_scan": "recommended"
}
}
EOF
)
echo "$threat_report" > "$threats_file"
if [[ ${#suspicious_apps[@]} -gt 0 ]] || [[ ${#unauthorized_apps[@]} -gt 0 ]]; then
echo "⚠️ Security threats detected!"
echo " Suspicious applications: ${#suspicious_apps[@]}"
echo " Unauthorized applications: ${#unauthorized_apps[@]}"
echo " Threat report: $threats_file"
# Send immediate alert if high-risk threats found
if [[ ${#suspicious_apps[@]} -gt 0 ]]; then
send_security_alert "$threats_file"
fi
else
echo "✅ No security threats detected"
fi
}
# Productivity analysis
analyze_productivity() {
local app_data="$1"
local analysis_file="$REPORTS_DIR/productivity_analysis_$(date +%Y%m%d_%H%M%S).json"
echo "=== Productivity Analysis ==="
# Categorize applications by productivity impact
local productive_apps=0
local neutral_apps=0
local distracting_apps=0
local total_apps=0
declare -A category_counts
while IFS= read -r app_line; do
if [[ -n "$app_line" ]]; then
local app_name=$(echo "$app_line" | jq -r '.name' 2>/dev/null)
local category=$(categorize_application "$app_name" "" "")
((total_apps++))
((category_counts["$category"]++))
case "$category" in
"productivity_apps"|"development_tools"|"communication_apps")
((productive_apps++))
;;
"system_utilities"|"creative_software")
((neutral_apps++))
;;
"entertainment_media"|"unknown_application")
((distracting_apps++))
;;
esac
fi
done <<< "$(echo "$app_data" | jq -c '.[]' 2>/dev/null)"
# Calculate productivity score (0-100)
local productivity_score=0
if [[ $total_apps -gt 0 ]]; then
productivity_score=$(( (productive_apps * 100 + neutral_apps * 50) / total_apps ))
fi
# Generate productivity report
local productivity_report=$(cat << EOF
{
"analysis_timestamp": "$(date -Iseconds)",
"hostname": "$(hostname)",
"productivity_metrics": {
"total_applications": $total_apps,
"productive_applications": $productive_apps,
"neutral_applications": $neutral_apps,
"distracting_applications": $distracting_apps,
"productivity_score": $productivity_score
},
"category_breakdown": $(for category in "${!category_counts[@]}"; do echo "\"$category\": ${category_counts[$category]}"; done | jq -s 'add'),
"recommendations": {
"productivity_level": "$([ $productivity_score -gt 80 ] && echo "excellent" || [ $productivity_score -gt 60 ] && echo "good" || [ $productivity_score -gt 40 ] && echo "moderate" || echo "needs_improvement")",
"focus_improvement": $([ $distracting_apps -gt 3 ] && echo "true" || echo "false"),
"suggested_actions": $([ $productivity_score -lt 50 ] && echo "[\"block_distracting_apps\", \"productivity_training\"]" || echo "[\"maintain_current_habits\"]")
}
}
EOF
)
echo "$productivity_report" > "$analysis_file"
echo "Productivity Analysis Results:"
echo " Total Applications: $total_apps"
echo " Productive: $productive_apps | Neutral: $neutral_apps | Distracting: $distracting_apps"
echo " Productivity Score: $productivity_score/100"
echo " Analysis Report: $analysis_file"
}
# Real-time monitoring session
start_monitoring_session() {
local profile="$1"
local duration="${2:-3600}" # Default 1 hour
local session_id="session_$(date +%Y%m%d_%H%M%S)"
local session_file="$DATA_DIR/${session_id}.json"
log_action "Starting monitoring session: $session_id (Profile: $profile, Duration: ${duration}s)"
# Initialize session data
cat > "$session_file" << EOF
{
"session_id": "$session_id",
"profile": "$profile",
"start_time": "$(date -Iseconds)",
"duration": $duration,
"hostname": "$(hostname)",
"monitoring_data": []
}
EOF
local end_time=$(($(date +%s) + duration))
local interval=30 # Monitor every 30 seconds
echo "Monitoring session started: $session_id"
echo "Duration: $duration seconds"
echo "Profile: $profile"
echo "Data file: $session_file"
while [[ $(date +%s) -lt $end_time ]]; do
local temp_file="/tmp/app_snapshot_$$.json"
# Get current application snapshot
get_comprehensive_app_info "$temp_file"
if [[ -f "$temp_file" ]]; then
local timestamp="$(date -Iseconds)"
# Add to session data
local snapshot=$(cat "$temp_file" | sed 's/^/ /')
# Update session file with new data point
jq --argjson snapshot "$(cat "$temp_file")" --arg timestamp "$timestamp" \
'.monitoring_data += [{"timestamp": $timestamp, "applications": $snapshot}]' \
"$session_file" > "${session_file}.tmp" && mv "${session_file}.tmp" "$session_file"
rm -f "$temp_file"
echo "$(date '+%H:%M:%S') - Snapshot captured ($(jq '.applications | length' <<< "$(cat "$temp_file")" 2>/dev/null || echo "0") apps)"
fi
sleep $interval
done
# Finalize session
jq '.end_time = "'"$(date -Iseconds)"'" | .status = "completed"' "$session_file" > "${session_file}.tmp" && mv "${session_file}.tmp" "$session_file"
log_action "Monitoring session completed: $session_id"
# Generate session analysis
analyze_monitoring_session "$session_file"
echo "✅ Monitoring session completed: $session_id"
echo "Session data: $session_file"
}
# Analyze monitoring session data
analyze_monitoring_session() {
local session_file="$1"
local analysis_file="${session_file%.json}_analysis.json"
if [[ ! -f "$session_file" ]]; then
log_error "Session file not found: $session_file"
return 1
fi
log_action "Analyzing monitoring session: $(basename "$session_file")"
# Extract session data
local session_id=$(jq -r '.session_id' "$session_file")
local profile=$(jq -r '.profile' "$session_file")
local start_time=$(jq -r '.start_time' "$session_file")
local end_time=$(jq -r '.end_time' "$session_file")
# Analyze application usage patterns
local most_used_apps
most_used_apps=$(jq -r '.monitoring_data[].applications[].name' "$session_file" | sort | uniq -c | sort -nr | head -10)
# Calculate session statistics
local total_snapshots=$(jq '.monitoring_data | length' "$session_file")
local unique_apps=$(jq -r '.monitoring_data[].applications[].name' "$session_file" | sort | uniq | wc -l)
local avg_apps_per_snapshot=$(jq '[.monitoring_data[].applications | length] | add / length' "$session_file")
# Security analysis
local security_events=0
local productivity_violations=0
# Generate comprehensive analysis
cat > "$analysis_file" << EOF
{
"session_analysis": {
"session_id": "$session_id",
"profile": "$profile",
"duration": {
"start_time": "$start_time",
"end_time": "$end_time"
},
"statistics": {
"total_snapshots": $total_snapshots,
"unique_applications": $unique_apps,
"average_apps_per_snapshot": $avg_apps_per_snapshot
},
"security_analysis": {
"security_events": $security_events,
"threat_level": "low",
"unauthorized_apps": []
},
"productivity_analysis": {
"productivity_violations": $productivity_violations,
"focus_score": 85,
"distracting_app_usage": 15
},
"compliance": {
"data_retention_compliant": true,
"monitoring_policy_compliant": true,
"privacy_settings_respected": true
}
}
}
EOF
echo "Session Analysis Completed:"
echo " Session ID: $session_id"
echo " Total Snapshots: $total_snapshots"
echo " Unique Applications: $unique_apps"
echo " Average Apps per Snapshot: $avg_apps_per_snapshot"
echo " Analysis File: $analysis_file"
log_action "Session analysis completed: $analysis_file"
}
# Fleet-wide application monitoring
deploy_fleet_monitoring() {
local fleet_config="$1"
local monitoring_profile="$2"
local duration="$3"
log_action "Starting fleet-wide monitoring deployment"
if [[ ! -f "$fleet_config" ]]; then
log_error "Fleet configuration file not found: $fleet_config"
return 1
fi
# Read fleet configuration
local hosts
hosts=$(jq -r '.hosts[]' "$fleet_config")
echo "Deploying monitoring to fleet..."
echo "Profile: $monitoring_profile"
echo "Duration: $duration seconds"
# Deploy to each host
while IFS= read -r host; do
if [[ -n "$host" ]]; then
echo "Deploying to: $host"
# Copy monitoring script to remote host
scp "$0" "root@${host}:/tmp/macfleet_monitor.sh" || {
log_error "Failed to copy script to $host"
continue
}
# Start monitoring session on remote host
ssh "root@${host}" "chmod +x /tmp/macfleet_monitor.sh && /tmp/macfleet_monitor.sh start_monitoring '$monitoring_profile' '$duration' &" || {
log_error "Failed to start monitoring on $host"
continue
}
log_action "✅ Monitoring started on: $host"
fi
done <<< "$hosts"
log_action "Fleet monitoring deployment completed"
}
# Generate comprehensive reports
generate_monitoring_report() {
local report_type="$1"
local report_name="${2:-monitoring_report_$(date +%Y%m%d_%H%M%S)}"
local report_file="$REPORTS_DIR/${report_name}.json"
log_action "Generating monitoring report: $report_name (Type: $report_type)"
case "$report_type" in
"daily_summary")
generate_daily_summary "$report_file"
;;
"security_audit")
generate_security_audit "$report_file"
;;
"productivity_analysis")
generate_productivity_report "$report_file"
;;
"compliance_report")
generate_compliance_report "$report_file"
;;
*)
log_error "Unknown report type: $report_type"
return 1
;;
esac
log_action "✅ Report generated: $report_file"
echo "Report saved to: $report_file"
}
# Alert system for critical events
send_security_alert() {
local threat_file="$1"
local alert_file="$ALERTS_DIR/security_alert_$(date +%Y%m%d_%H%M%S).json"
local threat_data=$(cat "$threat_file")
local threat_level=$(echo "$threat_data" | jq -r '.threat_level')
local suspicious_count=$(echo "$threat_data" | jq '.suspicious_applications | length')
# Generate alert
cat > "$alert_file" << EOF
{
"alert_type": "security_threat",
"severity": "$threat_level",
"timestamp": "$(date -Iseconds)",
"hostname": "$(hostname)",
"threat_summary": {
"suspicious_applications": $suspicious_count,
"threat_level": "$threat_level",
"immediate_action_required": $(echo "$threat_data" | jq '.recommendations.immediate_action')
},
"details": $threat_data
}
EOF
echo "🚨 SECURITY ALERT GENERATED: $alert_file"
log_action "Security alert generated: $alert_file"
audit_log "Security threat detected - Alert: $alert_file"
# In production environment, send to security team
# send_email_alert "$alert_file"
# send_slack_notification "$alert_file"
}
# Main function with command routing
main() {
local command="$1"
shift
# Initialize
create_directories
initialize_app_database
case "$command" in
"monitor")
# Basic one-time monitoring
local temp_file="/tmp/current_apps.json"
get_comprehensive_app_info "$temp_file"
if [[ -f "$temp_file" ]]; then
echo "=== Current Foreground Applications ==="
jq -r '.[] | "Application: \(.name) | PID: \(.pid) | Path: \(.path)"' "$temp_file"
rm -f "$temp_file"
fi
;;
"start_monitoring")
start_monitoring_session "$@"
;;
"security_scan")
local temp_file="/tmp/security_scan.json"
get_comprehensive_app_info "$temp_file"
if [[ -f "$temp_file" ]]; then
detect_security_threats "$(cat "$temp_file")"
rm -f "$temp_file"
fi
;;
"productivity_analysis")
local temp_file="/tmp/productivity_analysis.json"
get_comprehensive_app_info "$temp_file"
if [[ -f "$temp_file" ]]; then
analyze_productivity "$(cat "$temp_file")"
rm -f "$temp_file"
fi
;;
"deploy_profile")
deploy_monitoring_profile "$@"
;;
"fleet_deploy")
deploy_fleet_monitoring "$@"
;;
"generate_report")
generate_monitoring_report "$@"
;;
"show_categories")
print_application_categories
;;
"show_policies")
for policy in strict_compliance productivity_focused security_priority development_optimized creative_workflow executive_monitoring guest_restricted; do
echo "Policy: $policy"
echo " ${MONITORING_POLICIES[$policy]}"
echo ""
done
;;
*)
echo "MacFleet Enterprise Application Monitoring System"
echo "Usage: $0 <command> [options]"
echo ""
echo "Commands:"
echo " monitor - Get current foreground applications"
echo " start_monitoring <profile> [duration] - Start monitoring session"
echo " security_scan - Scan for security threats"
echo " productivity_analysis - Analyze productivity metrics"
echo " deploy_profile <profile> - Deploy monitoring profile"
echo " fleet_deploy <fleet_config> <profile> <duration> - Deploy to fleet"
echo " generate_report <type> [name] - Generate monitoring report"
echo " show_categories - Show application categories"
echo " show_policies - Show monitoring policies"
echo ""
echo "Examples:"
echo " $0 monitor"
echo " $0 start_monitoring productivity_focused 3600"
echo " $0 security_scan"
echo " $0 deploy_profile corporate_standard"
echo " $0 generate_report daily_summary"
;;
esac
}
# Execute main function with all arguments
main "$@"
Fleet Deployment Configuration
Fleet Configuration Example
{
"fleet_name": "MacFleet Corporate Network",
"deployment_date": "2025-07-07",
"hosts": [
"mac-dev-01.company.com",
"mac-design-01.company.com",
"mac-exec-01.company.com",
"mac-support-01.company.com"
],
"monitoring_schedule": {
"business_hours": "09:00-18:00",
"timezone": "UTC-8",
"weekdays_only": true
},
"global_settings": {
"data_retention": "90_days",
"reporting_frequency": "daily",
"alert_escalation": true
}
}
Monitoring Session Example
# Start 2-hour productivity monitoring session
./macfleet_monitor.sh start_monitoring productivity_focused 7200
# Security scan of current applications
./macfleet_monitor.sh security_scan
# Deploy corporate monitoring profile
./macfleet_monitor.sh deploy_profile corporate_standard
# Generate daily productivity report
./macfleet_monitor.sh generate_report daily_summary
Security Considerations
Application Security
- Threat Detection - Real-time scanning for malicious applications
- Unauthorized App Blocking - Prevent execution of non-approved software
- Behavioral Analysis - Monitor application usage patterns for anomalies
- Data Loss Prevention - Track applications with data access capabilities
- Encryption Verification - Ensure sensitive applications use proper encryption
Privacy Protection
- Configurable Screenshot Capture - Respect user privacy based on policies
- Personal Application Privacy - Separate monitoring for personal vs. business apps
- Data Anonymization - Remove personally identifiable information from reports
- Consent Management - Clear user consent for monitoring activities
Compliance Framework
Regulatory Compliance
- SOX Compliance - Financial application monitoring and controls
- HIPAA Compliance - Healthcare application security and access tracking
- GDPR Compliance - Data protection and privacy compliance
- PCI DSS - Payment application security monitoring
- NIST Framework - Cybersecurity framework implementation
Audit Requirements
- Comprehensive Logging - All application activities tracked and logged
- Data Retention Policies - Configurable retention based on compliance needs
- Access Controls - Role-based access to monitoring data and reports
- Chain of Custody - Secure handling of monitoring data and evidence
Troubleshooting Guide
Common Issues
AppleScript Permission Errors
- Grant permissions to
macfleetagentd
for Finder and System Events access - Check System Preferences > Security & Privacy > Privacy > Automation
- Verify MDM profile allows automation access
Incomplete Application Data
- Some applications may not report full information
- System applications might have limited metadata
- Sandboxed applications may restrict access to certain properties
Performance Impact
- Continuous monitoring can affect system performance
- Adjust monitoring frequency based on system capabilities
- Monitor system resources during extended monitoring sessions
Diagnostic Commands
# Test AppleScript execution
osascript -e 'tell application "System Events" to get name of every process whose visible is true'
# Check permissions
sqlite3 ~/Library/Application\ Support/com.apple.TCC/TCC.db "SELECT client,service,auth_value FROM access WHERE service='kTCCServiceAppleEvents';"
# Monitor system resources
top -l 1 -s 0 | grep "CPU usage"
Important Notes
- User Privacy - Respect user privacy and obtain proper consent for monitoring
- Performance Impact - Monitor system performance during extended monitoring sessions
- Data Security - Encrypt and secure all monitoring data and reports
- Compliance Requirements - Ensure monitoring practices meet regulatory requirements
- Regular Updates - Keep application signatures and threat detection patterns updated
- Documentation - Maintain detailed records of monitoring policies and procedures