Section 31. If a town by-law imposes a duty and affixes a penalty for the neglect or violation thereof, it may also provide that upon such neglect or violation the duty may be performed by officers therein named, at the expense of the person liable to perform the same; and such expense, to an amount not exceeding the penalty, may be recovered in contract by the town.