KABUL, Afghanistan — After months of besieging the northern Afghan provincial capital of Kunduz, Taliban fighters took over the city on Monday just hours after advancing, officials said, as government security forces fully retreated to the city’s outlying airport.

The Taliban’s sudden victory, after what had appeared to be a stalemate through the summer, gave the insurgents a military and political prize — the capture of a major Afghan city — that had eluded them since 2001. And it presented the government of President Ashraf Ghani, which has been alarmed about insurgent advances in the surrounding province for a year, with a demoralizing setback less than a year after the formal end of the NATO combat mission in Afghanistan.

Afghan officials vowed that a counterattack was coming, as commando forces were said to be flowing by air and road to Kunduz. But by nightfall, the city itself belonged to the Taliban. Their white flag was flying over several public areas of Kunduz, residents said.

Announcing their victory, the Taliban issued a statement saying that the group “has no intention” of looting or carrying out extrajudicial killings.