South Africa led 20-17 after an action-filled first half, Jesse Kriel going over early on and Handre Pollard adding a second try.
But Peter Horne finished off a breathtaking Scotland move and Hamish Watson went over after a clever line-out call.
After the break Willie Le Roux was sin-binned for a deliberate knock-on, but Scotland failed to take advantage.
South Africa's power and breakdown skills allowed saw emerge from the 10 minutes a man down with their three-point lead intact as Pollard and Greig Laidlaw traded penalties.
In a bruising final quarter, Finn Russell put a long-range drop-goal just wide, before Elton Jantjies nailed a long-distance penalty to stretch the lead to six.
And the Springboks held out impressively to inflict Scotland's first home defeat in a year, and the second of their autumn series.