The Pakistani Taliban has claimed responsibility for a gun and explosives attack on a university in the country's northwest that left at least 21 people dead.

A local police official said the operation had ended and security forces were clearing the area, with most of the student victims shot dead at a hostel for boys on the Bacha Khan University campus in Charsadda.

"Our four suicide attackers carried out the attack on Bacha Khan University today," a commander in the Tehreek-e-Taliban Pakistani (TTP) militant group said.

He added that the attack was in response to a military offensive against extremist strongholds in the tribal areas.

A spokesman for the army said on twitter that four of the gunmen had been killed by security forces and the army had contained the militants to two blocks inside the university.

Police said earlier that other attackers were believed to be at large on the second and third floors of the campus buildings.

The militants, using the cover of thick, wintry fog, scaled the walls of the university in Khyber Pakhtunkhwa province, before entering buildings and opening fire on students and teachers in classrooms and hostels, police said.

Mr Wazir said 70% of students had been rescued.

The Pakistani military's media wing said the army had cordoned off the university with the militants inside and were carrying out air surveillance.

Television footage showed soldiers entering the campus as ambulances lined up outside the main gate and anxious parents consoled each other.

Hundreds of suspected militants have been killed or arrested under a major crackdown launched after a massacre of 134 school children in December 2014 in the northwest.

The school attack by six gunmen believed linked to the Pakistani Taliban hit a raw nerve in Pakistan and was seen as having hardened Pakistan's resolve to fight jihadist militants along its lawless border with Afghanistan.

Vice Chancellor Fazal Rahim told reporters that the Bacha Khan University teaches over 3,000 students and had been hosting an additional 600 visitors today for a poetry recital.

Chemistry teacher hailed as a 'martyr' and a 'gentleman'

A chemistry teacher who tried to protect his students by opening fire on the Taliban militants has been hailed as a "martyr" and a "gentleman". 

Lecturer Syed Hamid Husain, an assistant professor of chemistry at the college in Charsadda, ordered his students to stay inside as the Taliban gunmen stormed the school. 

Students told of how he opened fire on the gunmen as they rampaged across campus, giving people time to flee before he was killed. 

One Geology student said that Mr Husain had warned him not to leave the building after the first shots were fired. He said the lecturer was holding a pistol in his hand when he was shot by two militants. 

Another student described the professor as a "real gentleman and a respectable teacher". 

Tributes have been paid to the teacher on Twitter.