After South Africa comfortably won the First Test in Johannesburg by 211 runs to start the three-Test series in emphatic fashion, Pakistan has now bounced back strongly over the first two days at Newlands.
Pakistan was in desperate trouble early on the opening day at 4-33 after being sent into bat by South African captain Graeme Smith, but outstanding fighting centuries from Khan and Shafiq got the tourists out of trouble, and towards posting a strong first innings score.
Even though Khan fell for 111 just before stumps, Pakistan was looking strong at 5-253 overnight but Shafiq could not add to his overnight score falling for 111 from 230 deliveries with 14 fours and a six.
He was out with the score 6-259 in just the second over of the day's play when caught at slip by Smith off Vernon Philander.
Pakistan was then 7-266 when Sarfraz Ahmed was out for 13, caught by Alviro Petersen off Philander and 8-268 with Umar Gul gone for a duck LBW to Philander as well, but then Tanvir Ahmed made a more than handy 44 with help from Ajmal (21 not out) and Mohammad Irfan (6).
That helped Pakistan make a competitive 338 for its first innings with Philander the pick of South Africa's bowlers claiming 5-59 from 26 overs. Morne Morkel took 2-59 before going off with an injured hamstring midway through his 21st over, Robin Peterson 2-94 and Dale Steyn 1-55.
South Africa's openers then made a solid enough start before captain Smith was the first to go with the score on 36.
South Africa looked reasonably comfortable against Pakistan's seam attack of Gul, Ahmed and the 7'1 left-arm debutant Irfan, but once Ajmal came on to bowl the game changed instantly.
He picked up the scalp of Smith when he trapped him in front for 19 and then four overs later picked up the wicket of Petersen for 17 also.
South Africa was then 2-50 when Hashim Amla and Faf du Plessis came together. They combined for 34 runs before Amla became Ajmal's third victim for 25 when also adjudged leg before wicket.
Soon after, the Proteas were 4-102 with Jacques Kallis gone for two, also LBW to Ajmal. Du Plessis lasted just seven more runs before he was caught by Khan off Ajmal for a fighting 28 off 83 deliveries.
AB de Villiers and Dean Elgar then safely saw South Africa through to stumps at 5-139 with de Villiers not out on 24 and Elgar on 11.
Ajmal has the outstanding figures of 5-41 from 25 overs for Pakistan and has claimed all five South African wickets to fall so far.
At stumps on the second day, South Africa is 5-139 and still trailing Pakistan by 199 runs with just five first innings wickets in hand.