The president cited the Sept. 11 attacks in his decision to issue the immigration restrictions, which he cast in national security terms. “We will never forget the lessons of 9/11,” he said, nor the people “who lost their lives at the Pentagon.”

But none of the 19 terrorists who were on the planes that crashed into the World Trade Center and the Pentagon and in Shanksville, Pa., were from any of the countries on Mr. Trump’s visa ban list.

Instead, Iraq, where the American military is fighting with Iraqi security forces against the Islamic State, is among the countries on the list. Military officials have repeatedly called the nation an American ally.

“After all the money and lives spent in Iraq and Afghanistan, the Pentagon knows better than anyone that terrorism is a problem of a small number of enemies embedded in a population of people you need to win over,” said Jon B. Alterman, director of the Middle East Program at the Center for Strategic and International Studies. “I don’t see the part of this that’s meant to win over anyone.”

Two people close to Mr. Mattis, who spoke on the condition of anonymity because they said they were wary of undercutting him, said he was still sharply opposed to the Muslim ban. But he spent this week battling the White House on other issues, including the establishment of “safe zones” in Syria, something the Pentagon has long opposed because it would deepen American involvement in the war there, out of the executive order.

Military officials sought to distance the Pentagon from the immigration ban, and focused instead on the second executive order that Mr. Trump signed at the Pentagon, which called for plans to improve military readiness. Mr. Mattis, standing behind Mr. Trump, took only the ceremonial pen that Mr. Trump used to sign the military readiness order. Mr. Trump gave the other one to Vice President Mike Pence.

Afterward, the Defense Department put out a statement about Mr. Trump’s visit to the Pentagon that pointedly made no mention of the Muslim ban. “The secretary shares the president’s goal of ensuring our military leaders have the support they need to accelerate the campaign against ISIS, and to build combat readiness now and for the future,” Capt. Jeff Davis, the Pentagon spokesman, said in the statement.

Last week, the Defense Department posted a message on Twitter about a former refugee who became a Marine. “From refugee to #Marine. @USMC Cpl Ali J. Mohammed takes the fight to the doorstep of those who cast his family out,” it read.