|
#!/bin/bash |
|
|
|
# === CONFIGURE YOUR DEVICE HERE === |
|
DEVICE_NAME="Kingston DataTraveler" |
|
PLIST_NAME="com.user.usbmonitor" |
|
MONITOR_SCRIPT="/usr/local/bin/usb_monitor.sh" |
|
PLIST_PATH="/Library/LaunchDaemons/${PLIST_NAME}.plist" |
|
LOGFILE="/tmp/usb-monitor.log" |
|
SUDOERS_BACKUP="/etc/sudoers.backup" |
|
|
|
echo "π Setting up USB Killswitch for device: $DEVICE_NAME" |
|
|
|
# --- Step 1: Create the monitor script --- |
|
echo "π Creating USB monitor script at $MONITOR_SCRIPT" |
|
|
|
cat <<EOF | sudo tee "$MONITOR_SCRIPT" > /dev/null |
|
#!/bin/bash |
|
|
|
DEVICE_NAME="$DEVICE_NAME" |
|
LOGFILE="$LOGFILE" |
|
|
|
while true; do |
|
USB_PRESENT=\$(system_profiler SPUSBDataType | grep -q "\$DEVICE_NAME" && echo "yes" || echo "no") |
|
|
|
if [ "\$USB_PRESENT" == "no" ]; then |
|
echo "\$(date): \$DEVICE_NAME removed, initiating shutdown" >> "\$LOGFILE" |
|
sudo /sbin/shutdown -h now |
|
exit |
|
fi |
|
|
|
sleep 2 |
|
done |
|
EOF |
|
|
|
sudo chmod +x "$MONITOR_SCRIPT" |
|
|
|
# --- Step 2: Create the Launch Daemon plist --- |
|
echo "βοΈ Creating launch daemon at $PLIST_PATH" |
|
|
|
cat <<EOF | sudo tee "$PLIST_PATH" > /dev/null |
|
<?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>$PLIST_NAME</string> |
|
<key>ProgramArguments</key> |
|
<array> |
|
<string>$MONITOR_SCRIPT</string> |
|
</array> |
|
<key>RunAtLoad</key> |
|
<true/> |
|
<key>KeepAlive</key> |
|
<true/> |
|
</dict> |
|
</plist> |
|
EOF |
|
|
|
sudo chown root:wheel "$PLIST_PATH" |
|
sudo chmod 644 "$PLIST_PATH" |
|
|
|
# --- Step 3: Load the Launch Daemon --- |
|
echo "π Loading launch daemon..." |
|
sudo launchctl load -w "$PLIST_PATH" |
|
|
|
# --- Step 4: Update sudoers for passwordless shutdown --- |
|
echo "π‘οΈ Updating sudoers to allow passwordless shutdown" |
|
|
|
# Backup sudoers file before modifying |
|
echo "π¦ Backing up /etc/sudoers to $SUDOERS_BACKUP" |
|
sudo cp /etc/sudoers "$SUDOERS_BACKUP" |
|
|
|
SUDOERS_TEMP=$(mktemp) |
|
sudo visudo -cf /etc/sudoers > /dev/null 2>&1 |
|
if ! grep -q "/sbin/shutdown" /etc/sudoers; then |
|
sudo bash -c "echo '%admin ALL=(ALL) NOPASSWD: /sbin/shutdown' >> /etc/sudoers" |
|
echo "β
Sudoers updated successfully." |
|
else |
|
echo "βΉοΈ Sudoers already contains shutdown rule. Skipping..." |
|
fi |
|
|
|
# --- Final Summary --- |
|
echo "" |
|
echo "β
USB Killswitch setup complete!" |
|
echo "π‘ Unplugging '$DEVICE_NAME' will trigger immediate system shutdown." |
|
echo "π οΈ Monitor script: $MONITOR_SCRIPT" |
|
echo "π LaunchDaemon: $PLIST_PATH" |
|
echo "π Log file: $LOGFILE" |