My DS started doing this at about 21 months I think and is still doing it at 3.4
Babies and toddlers have poor impulse control and this is why they lash out for no apparent reason. It gets better as they get older.
There's no point in punishing them for something they aren't even thinking about doing. When they have poor impulse control they don't think before they do it so they aren't going to remember any previous consequences to stop them from doing it again.
Your best bet is distraction and avoidance. If you take him to the park, soft play, someone's house or wherever stick to him like glue. Do not take your eyes off him. Encourage him to wave and say hello when he goes up to the other children. If you see him about to lash out say be kind, gentle, nice or whatever, allow him to stroke the person if they are happy for him to do so and guide him to something else. DS also has a special toy (a rubber light up ball with knobbly bits on) that he keeps in his pocket. Every time he attempts to hurt somebody and I manage to stop it the toy comes out so he can mess with that and it keeps his hands occupied. We are hoping eventually when he is frustrated he will learn to get the ball out by himself instead of lashing out.
It can also be an attention thing. Do you spend a lot of time getting down on the floor and playing with him or reading to him? I split the day up into 3 and make sure he gets a minimum of 10 minutes of undivided attention from me doing whatever he wants (within reason). We do from waking up to lunch time, lunch time until dinner time and then dinner time until bed. Typically we do floor play when he wakes up, drawing, building or chasing him around outside or throwing him around in the air in the afternoon and then stories, singing and cuddles before bed.
It has been going on for so long with DS we have been told taking him to a cranial osteopath can help. If it goes on for longer than a few months I would seriously consider doing it.