Aiden Markram, who top-scored with 91, looked to have marshalled South Africa’s fifth win in the tournament but his dismissal in the 41st over brought Pakistan back in the game.
Concussion substitute Usama Mir, a leg-spinner who replaced the injured Shadab Khan, opened up the game when he got the leading edge of Markram and Shaheen Afridi (3-45) found the outside edge of Gerald Coetzee to leave South Africa needing 21 with two wickets in hand.
Haris Rauf (2-62) then plucked a one-handed return catch off Lungi Ngidi’s leading edge to leave South Africa at 260-9 before Maharaj and Shamsi saw their team to the biggest run-chase in an ODI against Pakistan.
Pakistan has now lost four straight games at the World Cup for the first time and has four points from two victories against qualifiers the Netherlands and Sri Lanka.