Memoria USB de validación de Applescript - Número de serie y punto de montaje coincidentes

Quiero estar seguro de que la memoria USB en 'usbMountPoint' también es la que tiene el 'usbSerialNumber' coincidente

-- Get Mount Point of script's USB host
tell application "Finder"
   try
       set usbMountPoint to text 1 thru -2 of POSIX path of (disk of (path to me) as alias)
       log usbMountPoint --> Output: /Volumes/usb-drive-name
   on error
       set usbMountPoint to POSIX path of (disk of (path to me) as alias) --> if file is on desktop, path: '/', can't have ' ' hence no removing
       log usbMountPoint --> Output: /Volumes/usb-drive-name
   end try
end tell

-- Set Serial Num of USB Stick
set usbSerialNumber to "C86000BDB9F2BFA04A31E8A1"

-- Check if usbMountPoint and usbSerialNumber exist
set sysProfileUSB to (do shell script "system_profiler SPUSBDataType") as text
if sysProfileUSB contains "Serial Number: " & usbSerialNumber and sysProfileUSB contains "Mount Point: " & usbMountPoint then
   log "USB Stick Found!"
else
   log "USB Stick Not found."
end if

Al validar para verificar si usbMountPoint y usbSerialNumber existen en system_profiler, el código debe verificar si el dispositivo USB en 'usbMountPoint' tiene el número de serie de 'usbSerialNumber'. Sin esta "coincidencia/emparejamiento", el usuario simplemente podría tener dos USB conectados: uno con el número de serie correcto y el otro con el script; mientras que el código devolverá "Encontrado" porque 'contiene' lee todo el system_profiler sin validar que ambas variables provengan del mismo dispositivo.

Cualquier ayuda sería muy apreciada. Salud.

¿Te funcionó mi respuesta o te ayudó de alguna manera?

Respuestas (1)

Por supuesto, no conozco el alcance total de lo que está tratando de lograr, sin embargo, como actualmente lo tiene codificado, la secuencia de comandos podría ejecutarse desde otra unidad que no sea la unidad USB de destino. Así que lo he escrito un poco diferente, sin embargo, obtiene el punto de montaje en función del número de serie si la unidad USB de destino está montada. Luego puede bifurcarse de acuerdo con las condiciones, es decir, si el script se ejecuta desde la unidad USB de destino o no y si la unidad USB de destino está montada o no, etc. Después de obtener el punto de montaje en el código , he incluido otro bloque de códigopara probar si la unidad USB de destino está montada y desde dónde se ejecutó el script. Obviamente, esto es solo un ejemplo de prueba y tendrá que hacer lo que necesite. La conclusión aquí es cómo codifiqué obtener el punto de montaje de la unidad USB de destino en función del número de serie y supongo que esto es lo que realmente está buscando.

Esta es mi opinión sobre el código y su salida cuando se ejecuta tanto desde el escritorio como desde la unidad USB de destino:

  • Nota: Antes de usar, cambie el número de serie real a continuación al valor apropiado.

Código AppleScript:

--    # Get the volume this script is located on.

tell application "Finder"
    try
        set theVolumeThisScriptIsLocatedOn to text 1 thru -2 of POSIX path of (disk of (path to me) as alias)
        log "The volume this script is located on is: " & quoted form of theVolumeThisScriptIsLocatedOn
    on error
        set theVolumeThisScriptIsLocatedOn to POSIX path of (disk of (path to me) as alias)
        log "The volume this script is located on is: " & quoted form of theVolumeThisScriptIsLocatedOn
    end try
end tell

--    # Set the Serial Number of the target USB Drive.

set usbSerialNumber to "200434112111BA425FA4"

--    # See if the USB Drive matching 'usbSerialNumber' is mounted and if so, get its mount point.
--    # The variable 'usbMountPoint' will contain either its mount point, e.g., '/Volumes/...', or '' as in nothing.

set usbMountPoint to (do shell script "system_profiler SPUSBDataType | awk '/" & usbSerialNumber & "/' RS= | awk -F': ' '/Mount Point: /{print $2}'") as text
log "The mount point is: " & quoted form of usbMountPoint
if usbMountPoint is equal to "" then
    log "The target USB Drive is not mounted!"
else
    log "The target USB Drive is mounted!"
end if

--    # See if the script is running from the target USB Drive or elsewhere.

if usbMountPoint is not equal to "" and theVolumeThisScriptIsLocatedOn is equal to usbMountPoint then
    log "This script is running from the target USB Drive!"
else
    log "This script is not running from the target USB Drive!"
end if

Responde cuando se ejecuta desde la unidad USB de destino:

tell current application
    path to current application
        --> alias "16GB-USB:USB Test.scpt"
end tell
tell application "Finder"
    get disk of alias "16GB-USB:USB Test.scpt"
        --> alias "16GB-USB:"
    (*The volume this script is located on is: '/Volumes/16GB-USB'*)
end tell
tell current application
    do shell script "system_profiler SPUSBDataType | awk '/200434112111BA425FA4/' RS= | awk -F': ' '/Mount Point: /{print $2}'"
        --> "/Volumes/16GB-USB"
    (*The mount point is: '/Volumes/16GB-USB'*)
    (*The target USB Drive is mounted!*)
    (*This script is running from the target USB Drive!*)
end tell

Responde cuando se ejecuta desde el escritorio con la unidad USB de destino conectada:

tell current application
    path to current application
        --> alias "Macintosh HD:Users:me:Desktop:USB Test.scpt"
end tell
tell application "Finder"
    get disk of alias "Macintosh HD:Users:me:Desktop:USB Test.scpt"
        --> alias "Macintosh HD:"
end tell
tell current application
    path to current application
        --> alias "Macintosh HD:Users:me:Desktop:USB Test.scpt"
end tell
tell application "Finder"
    get disk of alias "Macintosh HD:Users:me:Desktop:USB Test.scpt"
        --> alias "Macintosh HD:"
    (*The volume this script is located on is: '/'*)
end tell
tell current application
    do shell script "system_profiler SPUSBDataType | awk '/200434112111BA425FA4/' RS= | awk -F': ' '/Mount Point: /{print $2}'"
        --> "/Volumes/16GB-USB"
    (*The mount point is: '/Volumes/16GB-USB'*)
    (*The target USB Drive is mounted!*)
    (*This script is not running from the target USB Drive!*)
end tell

Responde cuando se ejecuta desde el escritorio sin la unidad USB de destino conectada:

tell application "Finder"
    get disk of alias "Macintosh HD:Users:me:Desktop:USB Test.scpt"
        --> alias "Macintosh HD:"
end tell
tell current application
    path to current application
        --> alias "Macintosh HD:Users:me:Desktop:USB Test.scpt"
end tell
tell application "Finder"
    get disk of alias "Macintosh HD:Users:me:Desktop:USB Test.scpt"
        --> alias "Macintosh HD:"
    (*The volume this script is located on is: '/'*)
end tell
tell current application
    do shell script "system_profiler SPUSBDataType | awk '/200434112111BA425FA4/' RS= | awk -F': ' '/Mount Point: /{print $2}'"
        --> ""
    (*The mount point is: ''*)
    (*The target USB Drive is not mounted!*)
    (*This script is not running from the target USB Drive!*)
end tell

set usbMountPoint to (do shell script "...") as textComprender lo que hace la línea de comando para establecer el valor de la usbMountPoint variable .

  • system_profiler SPUSBDataType |genera toda la información relacionada con el hardware USB y luego se canaliza a la primera aparición de awken la línea de comando.
  • awk '/" & usbSerialNumber & "/' RS= |busca el número de serie y genera todo, desde la primera línea en blanco antes del número de serie y la primera línea en blanco después del número de serie y su salida luego se canaliza a la segunda aparición de awken la línea de comando. Esto garantiza que la única línea que contiene ' /Mount Point:' en la salida esté asociada con el número de serie (si la unidad USB de destino está montada).
  • awk -F': ' '/Mount Point: /{print $2}'encuentra la línea que contiene, 'Mount Point: 'luego la usa ': 'como separador de campo e imprime el segundo campo, que será el nombre de ruta POSIX del punto de montaje de la unidad USB de destino, o ''como nada (porque no estaba montado).