A prisoner tried to rape a female NYPD officer inside a Brooklyn courthouse on Friday — but a hero inmate helped stop the attack, police sources told The Post.

Jeriah Bamugo — who has been busted twice already this week on groping and menacing charges — was about to be hauled before a judge for arraignment in Brooklyn Criminal Court when he attacked, according to sources.

He pounced as the officer tried to transport him and another inmate from a holding cell into a courtroom at the Schermerhorn Street courthouse around 11:20 a.m.

The 26-year-old sicko allegedly grabbed the female officer, pinned her to the wall and growled, “I’m going to have sex with you” — all while ripping off her belt and clawing at her pants, multiple sources said.

They fell to the floor and that’s when a 17-year-old facing minor marijuana and theft charges leaped into action, attempting to shove Bamugo off of the cop.

Seconds later, the cop’s partner, who was standing outside the area where the cells are kept, rushed in to help, along with other nearby court officers.

“Thankfully, he was unsuccessful,” a law-enforcement source said of the attacker. “Another inmate saved her.”

Added another source, “He was trying to disrobe her, pulling at her clothes. Officers responded within 30 seconds. I saw one guy sprint back into the cells. The inmates immediately started screaming.”

The officer, whose name was withheld, is on modified duty and did not have a gun at the time.

She suffered a concussion and back injuries, and was taken to a nearby hospital for treatment.

Bamugo already faces a slew of charges in two other arrests that came within days of each other.

On Monday, he was charged with menacing, stalking and harassment for allegedly shoving a woman into a restroom at Kings County Hospital as she was exiting the lavatory, according to the criminal complaint.

Three days later, Bamugo was collared again for allegedly grabbing a woman’s breasts around 2:30 p.m. in East Flatbush. He also is accused of punching her on the shoulder before bolting, police said.

In that case, he was charged with forcible touching and assault.

Bamugo is expected to face additional charges of attempted rape of the officer, sources said.

His lawyer didn’t immediately respond to a request for comment.