Principales conclusiones
- Instalación automática: el script automatiza la instalación de ConnectWise Control en macOS, mejorando la eficiencia en los entornos de TI.
- Funciones de personalización: permite personalizar las instalaciones con el nombre de la organización, la ubicación del dispositivo, el tipo y el departamento.
- Tratamiento de errores: el script incluye un sólido sistema de gestión de errores y lógica de reintento para una descarga fiable.
- Flexibilidad en los parámetros: ofrece flexibilidad al aceptar varios formatos para los argumentos de la línea de comandos.
- Creación de URL: construye dinámicamente la URL de descarga adaptada a las necesidades específicas de la organización.
- Comprobación previa a la instalación: incluye una comprobación para evitar reinstalar ConnectWise Control si ya está presente.
- Consideraciones de seguridad: hace hincapié en la necesidad de garantizar el abastecimiento y la verificación de la integridad de los envases.
- Adaptabilidad: aunque está diseñado para macOS, el concepto del script se puede adaptar a otros sistemas o programas.
- Integración con herramientas de gestión de TI: destaca las sinergias potenciales del script con plataformas de gestión de TI más amplias, como NinjaOne.
La automatización y la eficiencia son cruciales en el panorama en constante evolución de la gestión de TI. Racionalizar la instalación de herramientas esenciales, como el software de asistencia remota, no sOlo ahorra un tiempo valioso, sino que también garantiza la coherencia en varios dispositivos. Este enfoque es especialmente significativo para los proveedores de servicios gestionados (MSP) y los profesionales de TI que gestionan una flota de máquinas.
Contexto
ConnectWise Control, anteriormente conocido como ScreenConnect, es una popular solución de asistencia remota, acceso y reuniones ampliamente utilizada en el sector de TI. Su adaptabilidad y su sólido conjunto de funciones lo convierten en una herramienta indispensable para los MSP y los departamentos de TI. El script en cuestión automatiza la instalación de ConnectWise Control en sistemas macOS. Esta automatización es especialmente vital para que los profesionales de TI y los MSP desplieguen este software de forma eficiente en varios dispositivos macOS, manteniendo la estandarización y reduciendo la carga de trabajo manual.
El script
#!/usr/bin/env bash
#
# Description: Download and Install ConnectWise ScreenConnect. Supports automatic customization of the company name, device type, location, and other ScreenConnect fields.
# 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: --screenconnectdomain "replace.me"
# Replace the text encased in quotes to have the script build the download URL and then install ScreenConnect.
#
# Preset Parameter: --useOrgName
# Modifies your URL to use the organization name in the "Company Name" field in ScreenConnect.
#
# Preset Parameter: --useLocation
# Modifies your URL to use the Location Name in the "Site" field in ScreenConnect.
#
# Preset Parameter: --useDeviceType
# Modifies your URL to fill in the "Device Type" field in ScreenConnect. (Either Workstation or Laptop).
#
# Preset Parameter: --Department "REPLACEME"
# Modifies your URL to fill in the Department name with the text encased in quotes.
#
# Preset Parameter: --skipSleep
# By default, this script sleeps at a random interval (between 3 and 30 seconds) before downloading the installation file.
# This option skips the random sleep interval.
#
# 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 automatically assumed a parameter is used.
_arg_instanceId=
_arg_screenconnectdomain=
# For parameters that don't have arguments "on" or "off" is used.
_arg_useOrgName="off"
_arg_useLocation="off"
_arg_useDeviceType="off"
_arg_department=
_arg_filename="ClientSetup.pkg"
_arg_destfolder=/tmp
_arg_skipsleep="off"
# Help text function for when invalid input is encountered
print_help() {
printf '\n\n%s\n\n' 'Usage: [--screenconnectdomain <arg>] [--useOrgName] [--useLocation] [--useDeviceType] [--department <arg>] [--skipSleep] [-h|--help]'
printf '\n%s\n' 'Preset Parameter: --screenconnectdomain "replace.me"'
printf '\t%s\n' "Replace the text encased in quotes with the domain used for ConnectWise ScreenConnect. ex. 'example.screenconnect.com'"
printf '\n%s\n' 'Preset Parameter: --useOrgName'
printf '\t%s\n' "Builds the url so the 'Company Name' field in ScreenConnect is filled in with the Organization Name."
printf '\n%s\n' 'Preset Parameter: --useLocation'
printf '\t%s\n' "Builds the url so the 'Site Name' field in ScreenConnect is filled in with the Location the device is in in Ninja."
printf '\n%s\n' 'Preset Parameter: --useDeviceType'
printf '\t%s\n' "Builds the url so the 'Device Type' field in ScreenConnect is filled in with the detected device type (Laptop or Workstation)."
printf '\n%s\n' 'Preset Parameter: --department "YourDesiredDepartmentName"'
printf '\t%s\n' "Builds the url so the 'Department' field in ScreenConnect is filled in with the text encased in quotes."
printf '\n%s\n' 'Preset Parameter: --skipSleep'
printf '\t%s\n' "By default this script will sleep at a random interval between 3 and 60 seconds prior to download. Use this option to skip this behavior."
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
--screenconnectdomain | --domain)
test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
_arg_screenconnectdomain=$2
shift
;;
--screenconnectdomain=*)
_arg_screenconnectdomain="${_key##--screenconnectdomain=}"
;;
--useOrgName | --useorgname | --orgname)
_arg_useOrgName="on"
;;
--useLocation | --useOrgLocation | --uselocation | --location)
_arg_useLocation="on"
;;
--useDeviceType | --usedevicetype | --devicetype)
_arg_useDeviceType="on"
;;
--department | --Department)
test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
_arg_department="$2"
shift
;;
--department=*)
_arg_department="${_key##--department=}"
;;
--skipsleep | --skipSleep)
_arg_skipsleep="on"
;;
--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 dynamic script variables are used override the comand line arguments
if [[ -n $screenconnectDomainName ]]; then
_arg_screenconnectdomain="$screenconnectDomainName"
fi
if [[ -n $useNinjaOrganizationName && $useNinjaOrganizationName == "true" ]]; then
_arg_useOrgName="on"
fi
if [[ -n $useNinjaLocationName && $useNinjaLocationName == "true" ]]; then
_arg_useLocation="on"
fi
if [[ -n $addDeviceType && $addDeviceType == "true" ]]; then
_arg_useDeviceType="on"
fi
if [[ -n $department ]]; then
_arg_department="$department"
fi
if [[ -n $skipSleep && $skipSleep == "true" ]]; then
_arg_skipsleep="on"
fi
# This function will download our file when we're ready for that.
downloadFile() {
i=1
while [[ $i -lt 4 ]]; do
if [[ ! $_arg_skipsleep == "on" ]]; then
sleep_time=$((3 + RANDOM % 60))
echo "Sleeping for $sleep_time seconds..."
sleep $sleep_time
fi
echo "Download Attempt $i"
curl -L "$url" -o "$_arg_destfolder/$_arg_filename" -s -f
file=$_arg_destfolder/$_arg_filename
if [[ -f $file ]]; then
echo 'Download was successful!'
i=4
else
echo 'Attempt Failed!'
((i += 1))
fi
done
}
# If we're not given a download method error out
if [[ -z $_arg_screenconnectdomain ]]; then
_PRINT_HELP=yes die "FATAL ERROR: The domain you use for ScreenConnect is required to install ScreenConnect." 1
fi
pattern='^http(.?)://(.*)'
if [[ $_arg_screenconnectdomain =~ $pattern ]]; then
_arg_screenconnectdomain=${_arg_screenconnectdomain//http*:\/\//}
echo "You accidentally included http with the domain. Using '$_arg_screenconnectdomain' instead."
fi
# If the destination folder doesn't exist create it.
if [[ ! -d $_arg_destfolder ]]; then
mkdir "$_arg_destfolder"
fi
# If a file already exists with that name remove it.
if [[ -f "$_arg_destfolder/$_arg_filename" ]]; then
rm "$_arg_destfolder/$_arg_filename"
fi
# Start the build process
echo "Building URL..."
# For anything we put in the url we'll need to escape it as curl won't do this conversion for us.
companyName=$(echo "$NINJA_COMPANY_NAME" | perl -MURI::Escape -ne 'chomp;print uri_escape($_),"\n"')
baseURL="https://$_arg_screenconnectdomain/Bin/$companyName.ClientSetup.pkg?e=Access&y=Guest"
# If the technician specified --useOrgName (or any other switch/flag) we set it to "on" when we parse the parameters
if [[ $_arg_useOrgName == "on" ]]; then
orgName=$(echo "$NINJA_ORGANIZATION_NAME" | perl -MURI::Escape -ne 'chomp;print uri_escape($_),"\n"')
baseURL="$baseURL&c=$orgName"
else
# If they decided to not use that field we just leave it blank so ScreenConnect will skip over it.
baseURL="$baseURL&c="
fi
if [[ $_arg_useLocation == "on" ]]; then
location=$(echo "$NINJA_LOCATION_NAME" | perl -MURI::Escape -ne 'chomp;print uri_escape($_),"\n"')
baseURL="$baseURL&c=$location"
else
baseURL="$baseURL&c="
fi
if [[ -n $_arg_department ]]; then
_arg_department=$(echo "$_arg_department" | perl -MURI::Escape -ne 'chomp;print uri_escape($_),"\n"')
baseURL="$baseURL&c=$_arg_department"
else
baseURL="$baseURL&c="
fi
# Getting whether or not the device is a laptop is a bit tricky. Fortunately only MacBooks are laptops (everything else is too old to worry about e.g. PowerBooks).
if [[ $_arg_useDeviceType == "on" ]]; then
modelName=$(system_profiler SPHardwareDataType -detaillevel mini | grep "Model Name" | sed 's/Model Name://' | xargs)
modelIdentifier=$(system_profiler SPHardwareDataType -detaillevel mini | grep "Model Identifier" | sed 's/Model Identifier://' | xargs)
if [[ $modelName == *"MacBook"* || $modelIdentifier == *"MacBook"* ]]; then
deviceType="Laptop"
else
deviceType="Workstation"
fi
baseURL="$baseURL&c=$deviceType&c=&c=&c=&c="
else
baseURL="$baseURL&c=&c=&c=&c=&c="
fi
url="$baseURL"
echo "URL Built: $url"
# At this point we should have everything setup for us to be able to download the file.
downloadFile
# Lets check if the download was a success
file="$_arg_destfolder/$_arg_filename"
if [[ ! -f $file ]]; then
_PRINT_HELP=no die "FATAL ERROR: The Installation File has failed to download please try again." 1
fi
# Analyze .pkg file and grab application name
pkgutil --expand $file "$_arg_destfolder/ScreenConnect"
pkgname=$(grep -Eo "connectwisecontrol-.*" "$_arg_destfolder/ScreenConnect/PackageInfo" | sed 's/".*//')
# Grabs a list of all installed packages and then filters it by connectwisecontrol-yourinstanceid
if [[ -z $pkgname ]]; then
echo "WARNING: Failed to get package name from .Pkg file. Checking if ANY ScreenConnect instance is installed."
installedPkg=$(pkgutil --pkgs | grep "connectwisecontrol-")
else
installedPkg=$(pkgutil --pkgs | grep "$pkgname")
fi
if [[ -n $installedPkg ]]; then
echo "Connectwise ScreenConnect is already installed!"
exit 0
else
echo "ConnectWise ScreenConnect is not installed. Installing..."
fi
# Start installing
echo "Installing application..."
if installer -pkg "$file" -target /; then
echo "Exit Code: $?"
echo "Connectwise ScreenConnect Installed Successfully!"
rm "$file"
exit 0
else
echo "Exit Code: $?"
rm "$file"
_PRINT_HELP=no die "FATAL ERROR: The Installation has failed!" 1
fi
Accede a más de 300 scripts en el Dojo de NinjaOne
Análisis detallado
El script comienza definiendo una serie de parámetros preestablecidos. Estos parámetros incluyen el dominio de ConnectWise, opciones para incluir el nombre de la organización, la ubicación y el tipo de dispositivo, junto con un identificador de departamento. Una característica notable es el parámetro «–skipSleep», diseñado para omitir un intervalo de suspensión aleatorio antes de iniciar la descarga, una adición inteligente para acelerar el proceso de instalación cuando sea necesario.
Una vez ejecutado, el script analiza primero los argumentos de la línea de comandos y establece las variables adecuadas en función de la información introducida por el usuario. Cabe destacar su flexibilidad para adaptarse a distintos formatos de parámetros (como –useOrgName y –useorgname), lo que facilita su uso.
A continuación, el script genera la URL de descarga del instalador de ConnectWise Control. Este paso consiste en añadir dinámicamente a la URL parámetros como el nombre de la organización, la ubicación y el tipo de dispositivo. Es una parte fundamental del script, ya que adapta el paquete de instalación a las necesidades específicas de la organización o el dispositivo.
El proceso de descarga, gestionado por la función downloadFile, incluye la gestión de errores y la lógica de reintento, lo que garantiza una descarga fiable incluso en condiciones de red poco ideales. El script intenta descargar el archivo hasta tres veces si es necesario, un enfoque sólido para gestionar posibles problemas de descarga.
Tras la descarga, el script comprueba si ConnectWise Control ya está instalado, lo que evita reinstalaciones innecesarias. Si no está ya instalado, procede a instalar el software.
Posibles casos de uso
Piensa en un MSP que gestiona la infraestructura informática de varias pequeñas empresas. Cada empresa puede tener configuraciones diferentes, como distintos departamentos o tipos de dispositivos. Con este script, el MSP puede implementar rápidamente ConnectWise Control en todos los dispositivos cliente, adaptándolo a la configuración específica de cada empresa, lo que aumenta la eficacia y reduce los errores manuales.
Comparaciones
Tradicionalmente, estas instalaciones requerían la descarga y configuración manual en cada dispositivo o el uso de herramientas de despliegue masivo que podían no ofrecer el mismo nivel de personalización. Este script proporciona un enfoque más racionalizado y personalizable, especialmente beneficioso para entornos con necesidades de configuración variadas y específicas.
FAQ
P: ¿Puede utilizarse este script para sistemas operativos distintos de macOS?
R: No, este script está diseñado específicamente para macOS.
P: ¿Es posible modificar el script para diferentes programas de asistencia remota?
R: Sí, con las modificaciones oportunas en la lógica de creación e instalación de URL, podría adaptarse a otro software.
Implicaciones
Aunque este script mejora enormemente la eficacia, es esencial tener en cuenta las implicaciones de seguridad. Los scripts automatizados pueden ser un vector de vulnerabilidades de seguridad si no se gestionan correctamente. Asegurarse de que el script procede de una URL segura y verificar la integridad del paquete descargado son pasos cruciales.
Recomendaciones
Las mejores prácticas incluirían revisiones y actualizaciones periódicas del script para adaptarse a cualquier cambio en el proceso de instalación de ConnectWise Control o a las actualizaciones de macOS. Además, es esencial asegurarse de que el script se ejecuta en un entorno seguro para evitar cualquier brecha de seguridad.
Reflexiones finales
En el contexto de NinjaOne, una plataforma unificada de gestión de TI, este script ejemplifica el tipo de eficiencia y automatización que puede integrarse en estrategias más amplias de gestión de TI. Tales scripts de automatización, cuando se combinan con una herramienta integral como NinjaOne, pueden mejorar significativamente la eficiencia y la eficacia de la gestión de TI, especialmente en entornos diversos y dinámicos.