With only four months to go in his second and last presidential term, he has raised a series of controversies intended, experts say, to reshape his public image and secure the support of dissatisfied urban Iranians for his handpicked successor, Esfandiar Rahim Mashaei. It is all part of a power struggle ahead of the June election between Mr. Ahmadinejad’s faction and a coalition of traditionalists, including many Revolutionary Guards commanders and hard-line clerics.

With the demise of the protest movement that sprang up after the last presidential election, in 2009, Mr. Ahmadinejad and his supporters have emerged in the unlikely role of the opposition. They are now fighting the traditionalists who, among other things, take a tougher line in negotiations with the West on Iran’s nuclear program and would like to abolish the presidency — a locus of opposition to their power.

In Iran’s complex politics, these struggles are typically waged under the watchful eye of the country’s supreme leader, AyatollahAli Khamenei, who ultimately decides the winners and losers, carefully balancing competing interests, to make sure no faction amasses too much power.

But this time, the jockeying for power is more than politics as usual. If the president and his supporters fail, they will lose any claim to immunity from prosecution and find themselves at the mercy not only of the judiciary but also of the country’s security forces, state television and influential Friday Prayer leaders, all controlled by the traditionalists.

Already, prosecutors have opened several files against Mr. Ahmadinejad’s lieutenants and are publicly warning them of possible prosecution on charges of financial corruption, mismanagement and deviating from Islam.

That is not to say that Mr. Ahmadinejad has had an epiphany and is ready to embrace Western democracy. Nor has he renounced his Holocaust denials and denouncements of Israel. But in recent months he has surprised his many critics in the West by challenging his enemies, sometimes in ways that are shockingly public.

In February, during a session of Parliament that was broadcast nationwide, he showed a secretly taped video of a meeting between one of his allies and Fazel Larijani, the youngest of five influential brothers closely associated with the traditionalists, who Mr. Ahmadinejad said was proposing fraudulent business deals.

At the funeral ofHugo Chávez, the Venezuelan leader, he was photographed embracing the former president’s mother, a display that was denounced by the clerics, who forbid physical contact between unmarried men and women who are not closely related. But urban Iranians, many of whom have moved far beyond the social restrictions set by the Islamic republic, viewed his action as a simple gesture of friendship.

Despite his early advocacy of Islam’s role in daily affairs, the president is now positioning himself as a champion of citizens’ rights. “He more and more resembles a normal person,” said Hamed, a 28-year-old driver in Tehran who did not want his last name used. “He doesn’t allow them to tell him what to do.”

In speeches, he favors the “nation” and the “people” over the “ummah,” or community of believers, a term preferred by Iran’s clerics, who constantly guard against any revival of pre-Islamic nationalism. He has also said he is ready for talks with the United States, something other Iranian leaders strongly oppose under current circumstances.

Mr. Ahmadinejad regularly brings up the topic of corruption by other officials, and he hints that they have accumulated wealth and power because of their positions. “Some of the relationships, which had been formed as a result of groupings and power-mongering pursuits in the country, have come to an end, and with the help of God will be purged from the revolution and the holy Islamic republic,” he asserted recently.

The president has also taken to using the slogan “long live spring” in his speeches, which some have interpreted as an allusion to the Arab Spring uprisings. “This way of thinking and talking about ‘Human Awakening’ is political mischief and dangerous,” one newspaper wrote in an editorial.

Mr. Ahmadinejad’s maneuvering is all about his legacy, experts say, an effort to preserve both his political power and his allies.

“In effect, the president has created a new current in Iran’s political establishment,” said Reza Kaviani, an analyst at the Porsesh Institute, which is aligned with Iran’s former president,Ali Akbar Hashemi Rafsanjani, a moderate opponent of Mr. Ahmadinejad. “He has organized himself, placed bureaucrats in key positions. He will outlive his two terms, and so will his friends. But how he will remain and at what costs is unclear for now.”

An error has occurred. Please try again later.

You are already subscribed to this email.

Mr. Ahmadinejad’s support of Mr. Mashaei, his spiritual mentor and the father-in-law of his son, is a particular stick in the eye for the conservatives, as well as a subtle appeal to more progressive Iranians. In messages filled with poetic language, Mr. Mashaei repeatedly propagates the importance of the nation of Iran over that of Islam.

Leading ayatollahs and commanders say that Mr. Ahmadinejad has been “bewitched” by the tall, beardless 52-year old, whom they have called a “Freemason,” a “foreign spy” and a “heretic.” They accuse Mr. Mashaei of plotting to oust the generation of clerics who have ruled Iran since the 1979 Islamic Revolution and of promoting direct relations with God, instead of through clerical intermediaries. He and his allies, they say, are part of a “deviant” current.

In response to Mr. Ahmadinejad, several opponents have warned about unrest and “sedition” around election time, comparable to the protests and riots after the president’s 2009 re-election, when millions took to the streets to dispute his victory.

“However, this time the scenario comes from figures who appear to be loyal and hold an office in the establishment,” Avaz Heydarpour, a lawmaker and critic of Mr. Ahmadinejad, told the Farda News Web site in March.

Those opposing Mr. Ahmadinejad are the same clerics and Revolutionary Guards commanders who supported Mr. Ahmadinejad’s candidacy in 2005 because he promoted religious values. They also backed him during the 2009 protests, cracking down on the opposition with blunt force at high political cost.

The presidency has evolved over time, starting out weak in the early years of the revolution but taking on greater importance after the abolition of the office of prime minister in the late 1980s. Once in office, presidents now create their own power bases, often clashing with the very people who backed their rise to power.

“All presidents in Iran start out under the patronage of a powerful faction,” said Heshmatollah Falahatpisheh, a former member of Parliament who is critical of Mr. Ahmadinejad. “But after they gain power they create their own circles and say they represent the people.”

The factional wrangling may well be a preview of what could unfold in Iran over the coming months. The first critical point may come if the Guardian Council, which vets candidates for public office, rejects Mr. Mashaei’s candidacy. In that case, said Ehsan Rastgar, a political scientist, “only the leader can decide.”

Ayatollah Khamenei has for now tried to calm the warring factions, repeatedly warning that their infighting is hurting the country’s interests.

Of late, the ayatollah has allowed Mr. Ahmadinejad to score victories in minor battles, like preventing Parliament from bringing him in for questioning. While both factions claim to have the ayatollah’s support, his position is unclear, and deliberately so, many Iran experts say.

If Mr. Mashaei’s candidacy is ultimately rejected by the Guardian Council, Ayatollah Khamenei can keep the peace by issuing a decree that would allow him to run, as he did for a reformist candidate in 2005.

“If Mr. Ahmadinejad refrains from all-out speeches with grandiose statements following a possible disqualification of Mr. Mashaei by the council, there is a chance the leader will allow him to run using a state decree,” Mr. Rastgar said. “If not, we might witness unrest.”

Correction: April 8, 2013

An article on Thursday about the power struggle that is gripping Iran ahead of the presidential election in June misstated the number of months before the end of President Mahmoud Ahmadinejad’s second and last term in office. It is four months, not three. (His successor will take office in August.)

A version of this article appears in print on April 4, 2013, on Page A1 of the New York edition with the headline: Power Struggle Gripping Iran Ahead of Vote. Order Reprints|Today's Paper|Subscribe