England captain David Beckham put Real ahead with a free kick after 15 minutes and Raul made it 2-0 to the Primera Liga leaders with eight minutes to go before halftime.
Leganes, from a working class suburb south of Madrid and featuring nine Argentine-born players in their team following a takeover by music tycoon Daniel Grinbank, came back to equalise before the end of the first half with two Borja goals.
The mid-table second division side went ahead five minutes after the break with a Francisco Pavon own goal and Real were heading out of the competition before Solari scored with a deflected shot two minutes from time.
Leganes missed a string of chances in the first period of extra-time and Real capitalised as Raul scored his second goal of the night five minutes into the second half.
A Real side missing the likes of Luis Figo and Zinedine Zidane but still boasting players of the calibre of Beckham, Roberto Carlos and Raul appeared to have the game wrapped up when they took a 2-0 lead in the first half.
Leganes goalkeeper Bernardo Leyenda was at fault on both goals, as he let a 30-metre free kick from Beckham slip through his fingers for the first and then dropped a weak shot from the England captain straight to the feet of Raul to tap in.
That should have been game over but a mistake from Raul Bravo gave Leganes a route back into the tie.
Bravo inexplicably allowed Pablo Ignacio Calandria to slip past him on the left side of the area and the Argentine forward provided a simple cross for Borja to touch past Cesar.
Borja, one of only two Spaniards in the Leganes side, levelled in the second minute of first-half injury-time as he nipped in front of the Real defence to glance a header past Cesar.
Leganes moved ahead just after the break when Pavon headed a Martin Ariel Vitali cross past his own keeper and that looked like being enough to take them through until Solari's late intervention tilted the tie Real's way.
More from rediff