Applescript : Lock & UnLock MacOS based on device stats I'm trying to do a script to lock my computer when a USB key is not connected and the other way , unlock my computer when the USB is connected.

I'm not quite sure how to do the second part, should I just remove Password requirement for unlocking when the USB is connected?

property Disconnected : true
property MyShellScript : missing value

on YubiKeyConnected()

    try
        set MyShellScript to do shell script "ioreg -c IOUSBDevice | grep Yubikey"
    on error
        set MyShellScript to "Not Connected"
        set Disconnected to true
    end try

    if MyShellScript contains "Yubikey NEO OTP+U2F+CCID@10" then

        set Disconnected to false
    end if
end YubiKeyConnected


on idle
    set currentState to YubiKeyConnected()
    if MyShellScript contains "Yubikey NEO OTP+U2F+CCID@ 10" then


    else if Disconnected is true then
        activate application "ScreenSaverEngine"
    end if
    return 1
end idle


Update : I found this but keep having the error "error "security: SecKeychainSearchCopyNext: The specified item could not be found in the keychain." number 44"

tell application "System Events"
    if ((get name of every process) contains "ScreenSaverEngine") then
        set pw to (do shell script "security find-generic-password -l \"[MyLocalPassword]\" -w")
        tell application "ScreenSaverEngine" to quit
        delay 0.5
        keystroke pw
        keystroke return
        -- set require password to wake of security preferences to false
    end if
end tell
delay 5

Can use this but not really secure :

tell application "System Events"
    if ((get name of every process) contains "ScreenSaverEngine") then
        set pw to "Password Here"
        tell application "ScreenSaverEngine" to quit
        delay 0.5
        keystroke pw
        keystroke return
        -- set require password to wake of security preferences to false
    end if
end tell