There most certainly is.
They are called launch daemons. On the Mac, there are two types:
Launch agents are run in a user context and have no elevated privileges
Lauch Daemons are run in a root context with elevated privileges
details available here:
https://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html
Now, the script itself is the easiest bit. Just write a .sh that contains a block of applescript wrapped in an osascript bundle, such as:
#!/bin/bash
osascript <<'END'
set bob to "hello"
say bob
END
You can, of course, call a script also with osascript scriptname.scpt
Now, and this is where it gets complex, you need to decide how to use your launch daemon. If you wanted to do this properly, you’d create an XPC service to listen for devices. As this is an AppleScript forum, that’s not what I’m going to propose:
Firstly, the plist needed for the Launch Agent
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.acme.yourlaunchagentname</string>
<key>Program</key>
<string>/Library/YourScriptLocation/com.acme.yourscript.sh</string>
<key>RunAtLoad</key>
<true/>
<key>StartInterval</key>
<integer>10</integer>
</dict>
</plist>
This will run every 20 seconds
Your com.acme.yourscript.sh will contain:
#!/bin/bash
osascript /Library/YourScriptLocation/yourscriptname.scpt
And your applescript will contain:
do shell script "touch ~/Devices_list.txt"
set old_device_number to do shell script "cat ~/Devices_list.txt"
if old_device_number = "" then
-- first time script run, write value and exit
do shell script "echo " & getDevicesNumber() & " > ~/Devices_list.txt"
else if old_device_number > getDevicesNumber() then
-- insert your stuff here when a device has been removed
do shell script "echo " & getDevicesNumber() & " > ~/Devices_list.txt"
log "something removed"
else if old_device_number < getDevicesNumber() then
-- insert your stuff here when a device has been added
do shell script "echo " & getDevicesNumber() & " > ~/Devices_list.txt"
log "something added"
else
-- no changes
log "no changes"
end if
on getDevicesNumber()
set devices_list_1 to do shell script "system_profiler SPUSBDataType | grep 'Product ID'"
set devices_list_2 to do shell script "system_profiler SPUSBDataType | grep 'Mount Point'"
set devices_number to (count of paragraphs of devices_list_1) + (count of paragraphs of devices_list_2)
return devices_number
end getDevicesNumber
Try running the AppleScript on it’s own, plugging devices in and removing them between runs, just to get a feel of how it works
Get your launch agents running and you should be good.