A much-changed Real side, missing the likes of Cristiano Ronaldo and Gareth Bale, held a 1-0 advantage from the first leg but their troubled season hit a new low as they were outplayed by a team lying 13th in La Liga.
Leganes started brightly and Claudio Beauvue sent a free kick against the post in the opening exchanges.
The visitors were deservedly level on aggregate after half an hour as a mishap between Achraf Hakimi and Nacho allowed Javier Eraso the space to produce a stunning finish from outside the box.
That appeared to bring about a reaction from the home side and Karim Benzema produced a neat finish from an acute angle immediately after the restart to put Zinedine Zidane’s men ahead on aggregate.
Leganes centre-back Dimitris Siovas missed a gilt-edged chance as he headed back across the six-yard box with the goal gaping, but moments later Gabriel Pires made no mistake as he thumped home a header to put Leganes through on away goals.
League leaders Barcelona host Espanyol on Thursday, trailing 1-0 from the first leg in the last quarter-final.