How to save the sudo password in AppleScript?

Solution 1:

Instead of temporarily storing your password in an application/AppleScript it might be easier to enable password-less sudo access to ping:

  • Run sudo visudo to open the sudoers file
  • Add a line %admin ALL=(ALL) NOPASSWD: /sbin/ping to give all users in the admin group password-less access to sudo ping

Afterwards you can just use sudo ping from Terminal or Applescript.

$ sudo ping -s 65000 askdifferent.com
PING askdifferent.com (104.27.182.101): 65000 data bytes
65008 bytes from 104.27.182.101: icmp_seq=0 ttl=56 time=1250.724 ms
65008 bytes from 104.27.182.101: icmp_seq=1 ttl=56 time=4.107 ms
65008 bytes from 104.27.182.101: icmp_seq=2 ttl=56 time=3.943 ms

This works even without enabling the root account.

PS: Never edit /etc/sudoers directly, always use sudo visudo to do so. visudo applies basic sanity checks on the file when saving, you risk to lock yourself out of sudo if you get things wrong by editing the file directly.

Solution 2:

  1. Use the Keychain Access.app to create a new keychain item (in the example jumboping), the (your?) admin name (in the example admin_name) and the (your?) admin password:

new keychain item

  1. Keychain item settings:

Keychain item access control

  1. Use this Apple Script (replace the two occurences of admin_name with the name of the (your?) admin account):

    on getPassword(keychainItemName)
        local password
        set password to do shell script "security find-generic-password -a admin_name -s jumboping -w"
    end getPassword
    
    set my_password to getPassword("PassKeychainName")
    
    do shell script "ping -s 65000 -c 3 192.168.0.7" user name "admin_name" password my_password with administrator privileges
    

    Result:

    "PING 192.168.0.7 (192.168.0.7): 65000 data bytes
    65008 bytes from 192.168.0.7: icmp_seq=0 ttl=64 time=4.865 ms
    65008 bytes from 192.168.0.7: icmp_seq=1 ttl=64 time=2.874 ms
    65008 bytes from 192.168.0.7: icmp_seq=2 ttl=64 time=3.878 ms
    
    --- 192.168.0.7 ping statistics ---
    3 packets transmitted, 3 packets received, 0.0% packet loss
    round-trip min/avg/max/stddev = 2.874/3.872/4.865/0.813 ms"
    

Note: The example AppleScript code is just that and does not contain any error handling as may be appropriate. The on getPassword(keychainItemName) routine retrieves the admin (sudo) password from the keychain and stores it in a variable - you will be asked for the keychain password once to allow security to access the keychain item. The do shell script "command" ... with administrator privileges line executes command with admin privileges but without the need to enter the sudo password. The admin (sudo) password stored in the keychain item jumboping can be used in any AppleScript or shell script!