Iran’s hierarchy often rails against the United States, Israel and Saudi Arabia as direct threats to its security and regional influence. But lately the authorities in Tehran have turned their attention to two new sources of worry: Lebanon and Iraq.

Enormous antigovernment demonstrations in both countries, some tinged with hostility and resentment toward Iran, have suddenly put Iran’s interests at risk. They have also raised the possibility of inspiring protests inside Iran itself.

If the Lebanese and Iraqi protesters succeed in toppling their governments and weakening established political parties with deep ties to Iran’s leaders, Iran stands to lose decades of financial, political and military investments that have turned it into one of the Middle East’s biggest powers.

On Wednesday, Iran’s supreme leader, Ayatollah Ali Khamenei, who is revered by some Lebanese and Iraqi Shiites as a spiritual leader, inveighed against the protests — a signal of the danger he sees lurking in them. Iran also closed several border crossings with Iraq to both travelers and trade, Iranian state media reported.