Gunmen stormed Kabul University on Monday, killing students in their classrooms and firing on others as they fled.
It is the second attack on an educational institution in the city in just over a week.
The three attackers killed at least 19 people including students before Afghan security forces shot the gunmen dead, authorities said.
"They were shooting at every student they saw ... they even shot at the students who were running away," witness Fathullah Moradi told Reuters.
The Taliban said their fighters were not involved in the assault. No other group immediately claimed responsibility.
Nineteen people were killed and 22 wounded before the security services ended the assault, interior ministry spokesman Tariq Arian said.
"This is the second attack on educational institutions in Kabul ... Afghan children & youth need to feel safe going to school," NATO Senior Civilian Representative to Afghanistan, Stefano Pontecorvo said in a statement.
A suicide bomber killed 24 people including teenage students at an education centre in Kabul on October 24. IS claimed responsibility for that attack, without providing evidence.
Violence has plagued Afghanistan while government and Taliban negotiators have been trying to broker a peace deal and as the United States brings home its troops.


Chinese national rescued from Nepal tunnel 10 days after flash flood
US envoys Witkoff, Kushner arrive in Moscow for talks on peace in Ukraine
One dead, 11 people missing after mudslide in China's Jiangxi province
Philippine VP Duterte posts bail after arrest order for alleged grave threats
Lindsay Clancy trial over killing her children ends in mistrial
Israel says it strikes southern Lebanon after Hezbollah drone launch
Sydney sweats in spring hot spell, faces 'extreme' bushfire risk
Nine days after disaster, two pulled alive from Nepal hydropower tunnel
