CAIRO — Saudi Arabia closed its embassy here on Saturday and recalled its ambassador, setting off a diplomatic crisis that seemed to catch Egypt’s military rulers off guard and left them struggling to repair a rift with a financial benefactor and a long-time ally.

The moves came after days of protests outside the embassy and Saudi consulates in Alexandria and Suez over the arrest of an Egyptian lawyer in Saudi Arabia this month. The Saudi news agency, citing an “official source,” said that the recall of the ambassador and the closings were the result of “unjustified demonstrations” and “hostile slogans,” and what the news agency said were attempts to “storm” the embassy.

Egyptian state media reported that the leader of Egypt’s ruling military council, Field Marshal Mohamed Hussein Tantawi, contacted the Saudi government and was working “to contain the situation in the light of the fraternal and historic relations between the two countries.”

The diplomatic dispute underscored the increasing willingness of Egyptian activists to assert muscular foreign policy demands, as well as to repudiate alliances cultivated over decades without public approval by autocratic rulers.