20241214/675d210846e38.jpeg

The best life is use of willing attitude, a happy-go-lucky life.

— Mr.Wang

头像

macos熄屏执行shell

发布时间:2024-12-14 14:09:12

发布作者:admin

68

1.Save this code1 as lockWatcher.swift2:

#!/usr/bin/env swift

import Foundation

class ScreenLockObserver {
    init() {
        let dnc = DistributedNotificationCenter.default()

        // listen for screen lock
        let _ = dnc.addObserver(forName: NSNotification.Name("com.apple.screenIsLocked"), object: nil, queue: .main) { _ in
            NSLog("Screen Locked")
            self.runBashScript(path: "~/bin/logout.sh")
        }

        // listen for screen unlock
        let _ = dnc.addObserver(forName: NSNotification.Name("com.apple.screenIsUnlocked"), object: nil, queue: .main) { _ in
            NSLog("Screen Unlocked")
            self.runBashScript(path: "~/bin/login.sh")
        }

        RunLoop.main.run()
    }

    private func runBashScript(path: String) {
        let task = Process()
        task.launchPath = "/bin/bash"
        task.arguments = ["-c", path]
        task.launch()
        task.waitUntilExit()
    }
}

let _ = ScreenLockObserver()
2.Make lockWatcher.swift2 executable:

chmod +x lockWatcher.swift
3.Run lockWatcher.swift2 on startup / login:

  1. Go to Settings -> General -> Login Items
  2. Click the + under the Open at Login list.
  3. And select the lockWatcher.swift2 file.


相关文章:
  1. 最完美解决Nginx部署ThinkPHP项目的办法
  2. 设置ulimit值(Linux文件句柄数量)永久生效
  3. MacOS 查看端口占用情况
  4. CentOS7 安装 Pure-ftpd