Principales conclusiones
- Este script automatiza la recuperación y el almacenamiento de las URL de inicio de ConnectWise Control en macOS, lo que agiliza considerablemente la asistencia remota.
- Ofrece opciones de personalización para identificadores de instancia, dominios, grupos de sesiones y campos personalizados, adaptándose a entornos de TI específicos.
- La inclusión de una función de ayuda y la gestión de errores mejoran la orientación del usuario y la resolución de problemas.
- El enfoque del script es más eficiente y organizado en comparación con la gestión manual de URL o las soluciones básicas de scripting.
- La seguridad y el acceso controlado a las URL generadas son esenciales para mantener la seguridad informática.
- Se recomienda probar el script en un entorno macOS específico antes de su despliegue completo.
- La integración de este script en un conjunto de herramientas más amplio como NinjaOne puede optimizar aún más el soporte remoto y las tareas de gestión de TI.
Contexto
En el actual panorama interconectado de las TI, la eficacia y la fiabilidad de la asistencia remota no son solo comodidades, sino necesidades. Los scripts avanzados, especialmente en el contexto de la gestión de software de asistencia remota, desempeñan un papel fundamental en la consecución de estos objetivos. El script del que hablamos hoy es un ejemplo de ello, ya que ofrece un método simplificado para gestionar las sesiones de ConnectWise Control (antes ScreenConnect) en macOS.
Este script Bash está diseñado para profesionales de TI y proveedores de servicios gestionados (MSP) que utilizan ConnectWise Control para la asistencia remota. Su función principal es recuperar y guardar las URL de inicio de ConnectWise Control, un componente crucial en la asistencia de escritorio remoto. Este proceso implica aprovechar los ID de instancia específicos, la información de dominio y los grupos de sesión para construir URL precisas y accesibles. Su importancia radica en la automatización de una tarea típicamente manual y lenta, lo que aumenta la productividad y los tiempos de respuesta de los equipos de soporte técnico.
El script
#!/usr/bin/env bash
#
# Description: Retrieves the Connectwise ScreenConnect Launch URL and saves it to a custom field (defaults to screenconnectURL). Requires the domain used for ScreenConnect and a Session Group that all machines are a part of to successfully build the URL.
# 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: --instanceId "ReplaceMeWithYourInstanceId"
# The Instance ID for your instance of ScreenConnect. Used to differentiate between multiple installed ScreenConnect instances.
# To get the instance ID, you can see it in the program name, e.g., connectwisecontrol-yourinstanceidhere.
# It's also available in the ScreenConnect Admin Center (Administration > Advanced > Server Information).
#
# Preset Parameter: --screenconnectDomain "replace.me"
# The domain used for your ScreenConnect instance.
#
# Preset Parameter: --sessionGroup "ReplaceMe"
# A session group that contains all of your machines (defaults to All Machines)
#
# Preset Parameter: --customField "ReplaceMeWithAnyMultilineCustomField"
# The custom field you would like to store this information in.
#
# 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_instanceId=
_arg_screenconnectdomain=
_arg_sessiongroup="All Machines"
_arg_customfield="screenconnectURL"
_fieldValue=
# Help text function for when invalid input is encountered
print_help() {
printf '\n\n%s\n\n' 'Usage: [--instanceId|-i <arg>] [--screenconnectDomain|-d <arg>] [--sessionGroup|-g <arg>] [--customField|-c <arg>] [--help|-h]'
printf '%s\n' 'Preset Parameter: --instanceid "ReplaceWithYourInstanceID"'
printf '\t%s\n' "Replace the text encased in quotes with your instance ID. You can see the instance ID in the ScreenConnect Admin Center (Administration > Advanced > Server Information). It's also usually present in the application name on any installed instance, e.g., connectwisecontrol-yourinstanceid."
printf '\n%s\n' 'Preset Parameter: --screenconnectDomain "replace.me"'
printf '\t%s' "Replace the text encased in quotes with the domain used for ConnectWise ScreenConnect, e.g., 'example.screenconnect.com'."
printf '\n%s\n' 'Preset Parameter: --sessionGroup "Replace Me"'
printf '\t%s' "Replace the text encased in quotes with the name of a Session Group in ConnectWise ScreenConnect that contains All Machines (defaults to All Machines). ex. 'All Machines'"
printf '\n%s\n' 'Preset Parameter: --customField "replaceMe"'
printf '\t%s' "Replace the text encased in quotes with the name of a custom field you'd like to store this information to (defaults to launchUrl). ex. 'screenconnectUrl'"
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 | --screenconnectDomain | --domain | -d)
test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
_arg_screenconnectdomain=$2
shift
;;
--screenconnectdomain=*)
_arg_screenconnectdomain="${_key##--screenconnectdomain=}"
;;
--instanceId | --instanceid | -i)
test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
_arg_instanceId=$2
shift
;;
--instanceid=*)
_arg_instanceId="${_key##--instanceid=}"
;;
--sessionGroup | --sessiongroup | -g)
test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
_arg_sessiongroup=$2
shift
;;
--sessiongroup=*)
_arg_sessiongroup="${_key##--sessiongroup=}"
;;
--customField | --customfield | -c)
test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
_arg_customfield=$2
shift
;;
--customfield=*)
_arg_customfield="${_key##--customfield=}"
;;
--help | -h)
_PRINT_HELP=yes die 0
;;
*)
_PRINT_HELP=yes die "FATAL ERROR: Got an unexpected argument '$1'" 1
;;
esac
shift
done
}
# Function to set a custom field
setCustomField() {
echo "$_fieldValue" | /Applications/NinjaRMMAgent/programdata/ninjarmm-cli set --stdin "$_arg_customfield"
}
export PATH=$PATH:/usr/sbin:/usr/bin
parse_commandline "$@"
# If script form is used override commandline agruments
if [[ -n $screenconnectDomain ]]; then
_arg_screenconnectdomain="$screenconnectDomain"
fi
if [[ -n $sessionGroup ]]; then
_arg_sessiongroup="$sessionGroup"
fi
if [[ -n $instanceId ]]; then
_arg_instanceId="$instanceId"
fi
if [[ -n $customFieldName ]]; then
_arg_customfield="$customFieldName"
fi
# If we weren't given an instance id we should warn that this is not advised.
if [[ -z $_arg_instanceId ]]; then
echo "WARNING: Without the instance id we will be unable to tell which ScreenConnect instance is yours (if multiple are installed). This may result in the wrong URL being displayed."
echo "To get the instance id you can find it in ScreenConnect itself (Admin > Advanced > Server Information > Instance Identifier Fingerprint). It's also in the application name on every installed copy 'connectwisecontrol-yourinstanceidhere'"
fi
# --screenconnectDomain and --sessionGroup are required. We should also escape the session group given.
if [[ -z $_arg_screenconnectdomain || -z $_arg_sessiongroup ]]; then
_PRINT_HELP=yes die "FATAL ERROR: Unable to build the URL without the Domain and Session Group!" 1
else
_arg_sessiongroup=$(echo "$_arg_sessiongroup" | perl -MURI::Escape -ne 'chomp;print uri_escape($_),"\n"')
fi
# Double check ScreenConnect is installed
installedPkg=$(pkgutil --pkgs | grep "connectwisecontrol-$_arg_instanceId")
if [[ -z $installedPkg ]]; then
_PRINT_HELP=no die "FATAL ERROR: It appears ConnectWise ScreenConnect is not installed!" 1
fi
# Lets start building some urls
for pkg in $installedPkg; do
file="/Applications/$pkg.app/Contents/Resources/ClientLaunchParameters.txt.lproj/locversion.plist"
id=$(grep -Eo 's=.{8}-.{4}-.{4}-.{4}-.{12}' "$file" | sed 's/s=//g' | sed 's/&e=Access//g')
instanceid=${pkg//"connectwisecontrol-"/}
# We shouldn't have multiple results but if we do we should warn the technician
if [[ -n "$launchurls" ]]; then
echo "WARNING: Multiple installed instances detected and no instance id was given. One of these urls will be incorrect."
launchurls=$(
printf '%s\n' "$launchurls"
printf '%s\t' "$instanceid"
printf '%s\n' "https://$_arg_screenconnectdomain/Host#Access/$_arg_sessiongroup//$id/Join"
)
else
launchurls=$(
printf '%s\t\t' "InstanceID"
printf '%s\n' "LaunchURL"
printf '%s\t' "$instanceid"
printf '%s\t' "https://$_arg_screenconnectdomain/Host#Access/$_arg_sessiongroup//$id/Join"
)
fi
done
# Check that we were successful
if [[ -n $launchurls ]]; then
echo "Launch URL(s) Created"
else
_PRINT_HELP=no die "FATAL ERROR: Failed to create Launch URL(s)!" 1
fi
# Change how we output the results based on how many urls we received.
if [[ $(echo "$launchurls" | wc -l) -gt 2 ]]; then
_fieldValue="$launchurls"
echo "$_fieldValue"
else
_fieldValue=$(echo "$launchurls" | tail -n 1 | awk '{print $2}')
echo "$_fieldValue"
fi
echo "Setting Custom Field..."
setCustomField
exit 0
Accede a más de 300 scripts en el Dojo de NinjaOne
Análisis detallado
El script funciona en varias etapas:
- Inicialización de parámetros: comienza estableciendo valores por defecto para varios parámetros como el ID de instancia, el dominio, el grupo de sesión y el nombre del campo personalizado.
- Función de ayuda: se incorpora una función de texto de ayuda, que guía a los usuarios en el uso del script, especialmente en casos de entradas no válidas.
- Análisis sintáctico de la línea de comandos: analiza los argumentos de la línea de comandos para personalizar parámetros como el dominio y el ID de instancia.
- Configuración del campo personalizado: el script incluye una función para establecer un campo personalizado en la herramienta NinjaRMM, donde se almacenará la URL de ConnectWise Control.
- Creación de URL de lanzamiento: la función principal consiste en crear las URL de lanzamiento extrayendo los ID necesarios de los paquetes instalados y construyendo la URL en base a los parámetros proporcionados.
- Gestión de la salida: en función del número de URL generadas, las almacena en un campo personalizado o las emite directamente.
Posibles casos de uso
Imagínate a un profesional de TI que gestiona una flota de dispositivos en diferentes organizaciones clientes. Necesita dar soporte remoto de forma ágil, pero gestionar los enlaces de cada sesión resulta pesado. Con este script, puede generar y almacenar rápidamente estas URL, garantizando un acceso remoto rápido y organizado.
Comparaciones
Tradicionalmente, los profesionales de TI podían configurar manualmente cada URL de sesión o utilizar scripts menos sofisticados. Este script, sin embargo, automatiza todo el proceso y está adaptado específicamente para ConnectWise Control en macOS, por lo que ofrece una solución más eficaz y sin errores.
FAQ
- ¿Cómo puedo encontrar el ID de instancia?
- Consulta el Centro de administración de ScreenConnect o el nombre de la aplicación en las instancias instaladas.
- ¿Es compatible con todas las versiones de macOS?
- Está diseñado para la compatibilidad general, pero siempre pruébalo primero en tu versión en específico.
- ¿Puedo personalizar el campo de almacenamiento para las URL?
- Sí, el script permite establecer un campo personalizado de tu elección.
Implicaciones
Aunque el script agiliza el proceso de gestión de sesiones remotas, es esencial tener en cuenta las implicaciones de seguridad. Garantizar que las URL se almacenan de forma segura y que el acceso está controlado es crucial para la seguridad informática.
Recomendaciones
- Actualiza periódicamente el script para adaptarlo a las nuevas actualizaciones de ConnectWise Control.
- Controla los permisos de seguridad de las URL almacenadas.
- Prueba el script en un entorno controlado antes de su despliegue generalizado.
Reflexiones finales
La incorporación de estos scripts en un conjunto de herramientas más amplio como NinjaOne puede mejorar significativamente la capacidad de un profesional de TI para gestionar el soporte remoto de manera eficiente y segura. El enfoque integral de NinjaOne para la supervisión y gestión remotas complementa estos scripts, proporcionando una plataforma sólida para la gestión de TI.