Lock keyboard from CLI I used to use kextload and kextunload to unlock/lock my keyboard. However, the actual kernel extension changes between MacBook  models, and that can have unexpected results.

For example, if the kext is AppleUSBTCKeyboard, both unloading and loading work fine. However, if the kext is AppleHIDKeyboard (e.g. MacBook Air), unloading works but loading again does not. This means kextunload -bundle-id com.apple.driver.AppleHIDKeyboard will disable the keyboard, but then it cannot be reenabled with kextload and the machine has to be rebooted.

There are some apps that are still able to do it, like KeyboardCleanTool. I’d prefer a CLI way of doing it, though. If possible (but won’t be picky) using only tools that come with macOS, or an open-source one.

Bonus points if there’s also a way to lock the trackpad, but that is less important.
One possibility could be to use ControllerMate.

You would have to create a Driver Configuration and map all of the keys to None.  Then there are multiple ways to enable/disable the custom Driver Configuration, but unfortunately CLI is currently not an option.

But CM is very customizable and I'm sure you could come up with something.  For example, using the logic blocks, you could have it disable when you have held down Z for 2 seconds, then hold down P and click the mouse.  Using a delay timer block to wait for 30 seconds but then only re-enable if holding the left shift key down and scrolling the mouse up/down.

Another similar utility that might work is Karabiner-Elements.  It is a complete rewrite of his wonderful Karabiner app which broke hard with macOS Sierra.  It is still in the early development stages but it might have the functionality you need.