Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!


Click here to return to the '[SOLVED] Run with administrative privileges' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
[SOLVED] Run with administrative privileges
Authored by: denydias on Sep 25, '08 01:20:35PM
Hi,

Asking to myself. :) Here's how I did it.

[code]
(* Original source : [http://www.macosxhints.com/comment.php?mode=display&format=threaded&order=ASC&pid=101884] *)


(* This is a script to automatically choose which volume to have time machine back up to. If the primary volume (= 1st in the list) is available, it will be chosen, otherwise it will choose any volume available in the list. If none is available, it will make no changes to the time machine preferences.
To use, set the names of the volumes here : *)

set backup_drives to {"preferred", "backup2", "backup3"}

(* Then launch the script whenever you want to change the time machine backup. The excellent utility DSW (http://www.azarhi.com/) can be used to launch the script whenever a volume is mounted or unmounted.
The script attempts to use growl to notify the user of its results.
Note that GUI scripting must be enabled *)

(* User interface elements required for UI scripting *)

(* Lists / listes / Listen / liste / listas / listas : 1) english, 2) français, 3) deutsch, 4) italiano, 5) español, 6) português do Brasil *)

(* Application (EN)
Application (FR)
Applikation (DE)
Applicazione (IT)
Aplicacion (ES)
Aplicação (PT_BR) *)

property names_prefs : {"System Preferences",
"Prfrences Système",
"Systemeinstellungen",
"Preferenze di Sistema",
"Preferencias del Sistema",
"Preferências do Sistema"}

(* Time machine *)

property names_tm : {"Time Machine",
"Time Machine",
"Time Machine",
"Time Machine",
"Time Machine",
"Time Machine"}

(* Preference pane list menu (EN)
Menu des panneaux de prfrences (FR)
Menu der Einstellungenfenster (DE)
Menu dei paneli di preferenze (IT)
Menu de las panelas da preferencias (ES)
Menu das Preferências do Sistema (PT_BR) *)

property names_view : {"View",
"Prsentation",
"Einstellungen",
"Vista",
"Visualización",
"Visualizar"}

(* Click the lock to make changes. (EN)
Pour modifier, cliquez sur le cadenas. (FR)
Klicken Sie auf das Schloss, um Änderungen vorzunehmen. (DE)
Modifiche disabilitate. (IT)
Haga clic aquí para realizar cambios. (ES)
Clique no cadeado para efetuar alterações. (PT_BR) *)

property names_lock : {"Click the lock to make changes.",
"Pour modifier, cliquez sur le cadenas.",
"Klicken Sie auf das Schloss, um Änderungen vorzunehmen.",
"Modifiche disabilitate.",
"Haga clic aquí para realizar cambios.",
"Clique no cadeado para efetuar alterações."}

(* Disc selection button (EN)
Bouton de slection du disque (FR)
Speicherauswahltaste (DE)
Bottone di schelta del disco (IT)
Botón di seleccion del disco (ES)
Botão de seleçõ do disco (PT_BR) *)

property names_usebutton : {"Use for Backup",
"Slectionner",
"Für backup verwenden",
"Utilizza per backup",
"Usar para copia de seguridad",
"Usar para Backup"}

(* Cancel button (EN)
Bouton d'annulation (FR)
Abbrechtaste (DE)
Bottone di annulatione (IT)
Botón di cancelatión (ES)
Botão cancelar (PT_BR) *)

property names_cancelbutton : {"Cancel",
"Annuler",
"Abbrechen",
"Annula",
"Cancelar",
"Cancelar"}

(* Quit command (EN)
Commande pour quitter (FR)
Beenden-Befehl (DE)
Istruzione per escire (IT)
Comando per salire (ES)
Comando Encerrar (PT_BR) *)

property names_quit : {"Quit System Preferences",
"Quitter Prfrences Système",
"Systemeinstellungen Beenden",
"Esci da Preferenze di Sistema",
"Salir de Preferencias del Sistema",
"Encerrar Preferências do Sistema"}

(* General notification (EN)
Notification gnrale (FR)
Allgemeine Meldung (DE)
Notificazione generale (IT)
Notificación general (ES)
Notificação geral (PT_BR) *)

property msgs_general : {"General notification",
"Notification gnrale",
"Allgemeine Meldung",
"Notificazione generale",
"Notificación general",
"Notificação geral"}

(* Error notification (EN)
Notification d'erreur (FR)
Fehlermeldung (DE)
Notificazione di errore (IT)
Notificación de error (ES)
Notificação de Erro *)

property msgs_error : {"ERROR",
"ERREUR",
"FEHLER",
"ERRORE",
"ERROR",
"ERRO"}

(* Success message (EN)




Message de succès (FR)
Erfolgsmeldung (DE)
Messagio di riuscita (IT)
Mensaje de xito (ES)
Mensagem de sucesso (PT_BR) *)

property msgs_newvolume : {"The Time Machine backup volume is now ",
"Le volume de sauvegarde de Time Machine est maintenant ",
"Der Zielspeicher für Time Machine ist nun ",
"Il disco di backup per Time Machine ora ",
"El disco de copia de seguridad de Time Machine es ahora ",
"O volume de backup ativo "}

(* Error message (EN)
Message d'erreur (FR)
Fehlermeldung (DE)
Messagio di errore (IT)
Mensaje de error (ES)
Mensagem de erro (PT_BR) *)

property msgs_notchanged : {"Time Machine preferences were not changed",
"Les prfrences de Time Machine n'ont pas t changes",
"Die Einstellungen von Time Machine wurden nicht geändert",
"Le preferenze di Time Machine non sono venuti cambiate",
"Las preferencias de Time Machine no han sido cambiadas",
"As preferências do Time Machine não foram alteradas"}

(* Language not found message *)

property msg_language : "ERROR - language not found" & return &
"ERREUR - langue non trouve" & return &
"FEHLER - Sprache nicht gefunden" & return &
"ERRORE - lingua non trovata" & return &
"ERROR - lingua no trovada" & return &
"ERRO - Idioma não encontrado"

property growl_general : "General Notification" -- Growl notification types
property growl_debug : "Debug Notification"
property growl_error : "Error Notification"

register_growl() -- register with Growl notification system

activate application "System Preferences" -- activate or launch preferences

tell application "System Events" -- get the localized_name of the System Preferences application
set loc_name to displayed name of process named "System Preferences"
end tell

global lg -- allow language index to be accessed from subroutines

set lg to 0 -- find out the language used by system preferences
repeat with i from 1 to count names_prefs
if item i of names_prefs = loc_name then
set lg to i
exit repeat
end if
end repeat

if lg = 0 then -- language not found - exit with error
growlnote(growl_error, item 1 of msgs_error, msg_language)
else

set name_tm to item lg of names_tm -- get name of Time Machine because it is used quite often

tell application "System Events"
tell process "System Preferences"

delay 1 -- give it a time to load and get ready (avoid errors)

click menu item name_tm of menu 1 of menu bar item (item lg of names_view) of menu bar 1 -- directly activate Time Machine panel from menu

repeat until exists window name_tm -- wait for Time Machine Preferences to load
delay 0.2
end repeat

(* Get credentials and authenticate to go *)
if button 4 of window name_tm exists then -- authenticate if needed
if title of button 4 of window name_tm is item lg of names_lock then -- authenticate if unauthorized

activate "System Events"
set credentials to {1, 2}
set item 1 of credentials to display dialog "Digite um nome de administrador." with icon (path to resource "FileVaultIcon.icns" in bundle ((path to library folder from system domain as string) & "CoreServices:CoreTypes.bundle") as alias) with title "Time To Go" default answer "" buttons {"Cancel", "OK"} default button 2 giving up after 60 -- !!!remember to translate "Digite um nome de administrador." (Type an administrator username.) to your language.
set item 2 of credentials to display dialog "Digite a senha do administrador." with icon (path to resource "FileVaultIcon.icns" in bundle ((path to library folder from system domain as string) & "CoreServices:CoreTypes.bundle") as alias) with title "Time To Go" default answer "" buttons {"Cancel", "OK"} default button 2 giving up after 60 with hidden answer -- !!!remember to translate "Digite a senha do administrador." (Type an administrator password.) to your language.

click button 4 of window name_tm -- open the locker

tell application "System Events" -- authentication
tell window 1 of process "SecurityAgent" -- call authentication agent
set value of text field 1 of scroll area 1 of group 1 to text returned of item 1 of credentials
set value of text field 2 of scroll area 1 of group 1 to text returned of item 2 of credentials
click button 2 of group 2
end tell
end tell

if sheet 1 of window 1 of process "SecurityAgent" of application "System Events" exists then -- check if authentication failed
click button 1 of sheet 1 of window 1 of process "SecurityAgent" of application "System Events"
click button 1 of group 2 of window 1 of process "SecurityAgent" of application "System Events"
tell application "System Preferences" to quit -- quit preferences
activate "System Events" -- focus dialog
display dialog "Autenticação falhou. Tente novamente." with icon stop buttons {"Cancel"} with title "Time To Go" default button 1 -- let the user know it failed !!!Remember to translate "Autenticação falhou. Tente novamente." (Authentication Failed. Try Again.) to your language.
end if
end if
end if

click button 1 of group 1 of window name_tm -- change disk button

(* Choose 1st available disk *)
repeat until exists sheet 1 of window name_tm -- wait till disk change dialog comes up
delay 0.2
end repeat

set tablecontents to (rows of table 1 of scroll area 1 of sheet 1 of window name_tm) -- traverse disk list
set rownumber to 0
set desiredrownumber to 0 -- reset row number (in volume list) of desired volume
set desired_name to "" -- reset desired volume name
set preferred_name to item 1 of backup_drives -- get name of the preferred / primary backup volume = 1st in the list
repeat with tablerow in tablecontents
set rownumber to rownumber + 1
set volumename to (value of static text of row rownumber of table 1 of scroll area 1 of sheet 1 of window name_tm) as string
log volumename
if (volumename as string) is in backup_drives then -- found a volume in the list
set desiredrownumber to rownumber -- set the desired row number in volume list
set desired_name to volumename -- set the desired volume name
if desired_name = preferred_name then exit repeat -- keep this one if this is the primary volume
end if
end repeat
if desiredrownumber > 0 then
try
select row desiredrownumber of table 1 of scroll area 1 of sheet 1 of window name_tm -- select the desired volume in list
click button (item lg of names_usebutton) of sheet 1 of window name_tm -- click the localised "use" button
set message_title to (item lg of msgs_general) -- tell user that a backup volume has been successfully selected
set message to (item lg of msgs_newvolume) & desired_name
my growlnote(growl_general, message_title, message)

on error
set desiredrownumber to 0 -- if failure for some reason, reset row number to 0 = nothing
end try
end if

if desiredrownumber = 0 then -- error message if unsuccessful
try -- try to cancel
click button (item lg of names_cancelbutton) of sheet 1 of window name_tm -- click the localised "Cancel" button
end try
set message_title to (item lg of msgs_error) -- not found : tell user that the preferences weren't changed
set message to item lg of msgs_notchanged
my growlnote(growl_error, message_title, message)
end if

delay 1 -- wait for a confirmation dialog that appears if you select a partition on the same physical disk as that being backed up
if (exists button (item lg of names_usebutton) of window 1) then
click button (item lg of names_usebutton) of window 1
end if

if title of button 4 of window name_tm is not item lg of names_lock then
click button 4 of window name_tm -- Close the locker
end if

delay 1 -- wait for the closed locker
end tell
end tell
tell application "System Preferences" to quit -- quit preferences
end if

(* Try to register script with Growl *)

on register_growl()
try
tell application "GrowlHelperApp"
set the allNotificationsList to {growl_general, growl_debug, growl_error} -- Growl notifications
set the enabledNotificationsList to {growl_general, growl, debug, growl_error} -- Those enabled for this app
register as application "Configure Time Machine" all notifications allNotificationsList default notifications enabledNotificationsList icon of application "Time Machine"
end tell
end try
end register_growl

on growlnote(growltype, msg_title, msg_text)
try
tell application "GrowlHelperApp"
notify with name growltype title msg_title description msg_text application name "Configure Time Machine"
end tell
end try
end growlnote
[/code]

Some considerations:
1 - It will ask for admin user/pass credentials and store it in memory during runtime. This method is safer than simple set it in a script variable but less secure than call SecurityAgent directly to athenticate (which I don't know how to do using AppleScript).
2 - The click in the locker and authentication process is localized just as the original script by tmaeder (tks again, bro!).
3 - The dialogs I created to ask for user, password and to let the user know if authentication failed is not localized. You must edit the script to make it read right in your language. I provided english translation in the line comment as a base.
4 - Sometime the script fails to click in the System Preferences menu (it's not my fault, this happens since the original script). In this case, I recommend you to run it again. Set a shortcut to run it or set a QuickSilver's trigger (I'm using this one).
5 - If the authentication fail (wrong user/pass typed), the script will close System Preferences and exits gently. In this case, rerun it using the shortcut or trigger.

That's all folks. It's being really helpfull to me. I hope it could be the same for others out there.

Best,


[ Reply to This | # ]