An ex-Marine “went into combat mode” against a crazed vandal and beat him senseless when he was attacked at the fancy Upper East Side apartment building where he works as a doorman, according to law-enforcement sources.

Andy Frederick, 48, was working the overnight shift in the lobby of the building at 44 East 67th St. around 1:50 a.m. on Friday, when he saw Betzelel Levin, 29, walking by and then heard glass shattering, sources said.

Frederick dashed outside and approached Levin, who allegedly had busted one of the building’s windows and was about to kick in another.

“The guy struck [Andy] in the chest. [Andy] automatically went into combat mode and used his hands to defend himself,” said Frederick’s brother, Mario.

Frederick allegedly pummeled Levin in the face until he incapacitated him.

The doorman, who is studying at Brooklyn College to become a teacher, then dragged Levin inside the building to keep an eye on him while calling 911.

Levin, who was charged with attempted assault and criminal mischief, was treated and released at New York Hospital, authorities said.

jamie.schram@nypost.com