If you are willing to throw a bit of money rather than code at the problem:
Ubiquiti has a power strip in beta now that uses statistics from their routers to decide when to power cycle upstream devices.
You can also find "Web Power Switches" (https://www.amazon.com/dp/B0765NCB2L) under $200 that are scriptable, so when a ping to a specific site fails it cycles power to a set of devices.