I've never done it but always thought that it would be good to install a bear spray system in the cockpit that I could trigger from inside my locked companionway. A simple system of a couple of cans of bear spray (one on each side of the cockpit door shooting back at anyone in the area) on a pull trigger from below.
If we're below decks at night and we hear noise at the companionway we could trigger it and then set off an air horn. That should make the thugs scatter pretty quickly. Of course,we'd have to lock ourselves in for it to work. We do that quite a bit anyway as we don't want any surprises in the middle of the night.
Always wanted to do that.