I may have a console command fix to stop your settlements from being attacked.
I have tried this myself for over 20 hours and have not had any settlements attacked that use this code. The thing is, I'm still not convinced it is 100% effective, so I want others to try it out and see if it works for them too. It seems that the game uses the ownership of the workshops as one of the criteria for deciding a settlement attack. So if one changes the ownership, in theory, the settlement should fail the check.
To do this, you have to be on PC and visit each workshop individually.
Open the console and click on the workshop workbench so its Ref ID is visible then type:
setownership 35DE
Isowner
The last line isn't required but is used to verify that the owner is not the player.
That's it. The first line sets the owner of the workshop to the Generic NPC Faction and doesn't seem to affect anything else in the game.
If you ever want to set ownership back, just do the same commands minus the Ref ID (35DE) and the workshop will be owned by the player once again.