BAGHDAD — Hundreds of Sunni militants stormed the central Iraqi city of Samarra early Thursday, taking control of neighborhoods and government buildings in a siege that provoked a panicked government counteroffensive to prevent the loss of the town.

The army rushed troops, backed by helicopters, to Samarra, and by Thursday evening, government officials claimed that the gunmen had largely been routed. Residents, though, said that at least two neighborhoods remained at least partly under control of the militants, who raised the flag of the Islamic State of Iraq and Syria over several government buildings.

At least 17 people were killed in the fighting. The brazen offensive provided the latest evidence of the militants’ strength in Iraq, six months after hard-line Islamist fighters seized the western city of Falluja, which militants continue to control. The attack also raised the specter of deadly sectarian incitement, as the heavily armed militants took up positions within a mile of a hallowed Shiite shrine in the city that has served as a focal point for strife in the past.

The bombing of the dome of the shrine in 2006 set off rounds of retaliatory violence against Sunni mosques and unleashed some of the bloodiest sectarian fighting of the Iraqi civil war. On Thursday, officials appeared determined to protect the site, saying that heavy security details had been sent there while insisting that it remained beyond the reach of the militants’ weapons.