Pakistan is observing a day of mourning after Islamic militants stormed a university, gunning down students and teachers and spreading terror before the four gunmen were killed by the military.

The death toll from the assault at Bacha Khan University in the town of Charsadda, near Peshawar, rose to 21 after another student died in hospital, according to police official Tariq Khan.

Flags on official buildings and parliament are flying at half-mast and police have stepped up security at schools and educational centres across the country.

A breakaway Taliban faction took responsibility for the university attack on Wednesday, which raised grim echoes of the 2014 school massacre that left 150 dead, 144 of them children.

Two teachers were among the dead, including a chemistry professor who was praised as a hero for shooting back at the attackers and allowing some students to escape.

"My son was grown up, but still he was an innocent kid for me," said Gula Bibi, the mother of the second killed teacher, Iftikhar Ahmad, who was the university librarian.

"My heart is breaking apart, I don't know what to do," she said.

The attack, which also wounded 22 students, again raised questions about whether security forces can protect the country's educational institutions from extremists.

The university in Charsadda is named after one of Pakistan's greatest secular leaders who often espoused communist philosophy, Abdul Ghaffar Khan, also known as Bacha Khan. The attack coincided with the 28th anniversary of his death on January 20 1988.

Most of the victims were buried quickly, according to Muslim tradition, with funerals overnight and early on Thursday, said police.

Mohammad Khurasani, a spokesman for the main Taliban group in Pakistan, disowned the outfit behind the university attack, terming it "un-Islamic" and insisted the Pakistani Taliban was not behind it.

Bacha Khan University remains closed and its vice chancellor Fazal-ur-Rahim Marwat said classes would resume Monday.

"We need time to clean the campus, make more security arrangement and boost the morale of the students and teachers," he said.

Pakistani prime minister Nawaz Sharif said his country is increasingly determined to fight extremism after the university attack by Islamic militants.

Mr Sharif said the country's resolve to fight against these elements is "getting stronger every day".

He said the attack was the result of "blowback" after Pakistani authorities' efforts to dismantle extremists' infrastructure and hide-outs.

Even as his country mourned the students killed at Bacha Khan university, Mr Sharif insisted that the extremists' ability to strike back "has been considerably destroyed". The terrorists are "on the run", he insisted.