"We believe that the forces that came from overseas and travelled thousands of kilometres to reach here must leave the region, and must hand over responsibility to people of the region.
"The presence of foreigners in the region is nothing but a humiliation to the regional nations."
It was the first visit of an Iranian leader to Iraq since the Iranian revolution in 1979 and saw seven treaties signed.
These included agreements on trade, industry and transport.
On Sunday, Ahmadinejad cried when visiting the shrine of Imam Musa al-Kadhim – one of the most revered Shia sites. The midnight trip was a religious focal point of a tour dominated by diplomacy.
The US has accused Iran of supplying weapons to opponents of US and Iraqi government forces in Iraq. They say these opponents are factions of the Mahdi Army of Muqtada al-Sadr, the radical Shia cleric.
However, during the trip Ahmadinejad had a televised meeting with Abdul-Aziz al-Hakim, Iraq's most powerful Shia political leader who supports the Iraqi government and is al-Sadr's rival.
The Iranian president also held hands and embraced Jalal Talabani, the Iraqi president.
The moves were made to show the increased closeness of the Iranian government to its Iraqi counterpart - which are both governed by Shia majorities - and a movement away from al-Sadr.
Saddam Hussein, Iraq's former president and a Sunni, led a war against Iran from 1980 to 1988. The war claimed an estimated one million lives.
The White House has dismissed the importance of Ahmadinejad's visit and reiterated that Iran was supporting radical groups in Iraq.