Javier Eraso levelled the scores on aggregate before Karim Benzema restored Real's aggregate lead.
Brazilian midfielder Gabriel hit Leganes' winner as the visitors advanced to the semi-finals on the away goals rule.
Real were without both Cristiano Ronaldo and Gareth Bale for the game against their near neighbours, who were playing in the third tier of Spanish football four years ago.
Yet Zinedine Zidane's side still included established players including defender Sergio Ramos, midfielder Isco and striker Benzema.
The Real boss is expected to come under renewed pressure after yet another defeat.
The 19-time Copa del Rey winners have lost four La Liga games this season and trail leaders Barcelona by 19 points.
Their last realistic hope of silverware this season rests with the Champions League.
The 12-time European champions face a tough tie with Paris St-Germain in the last 16, with the first leg in Madrid on 14 February.
This will go down as a famous night for Leganes, who lie 13th in La Liga.
They had lost all five of their previous league and cup games with Real. PLACE YOUR TEXT ADVERT BELOW:>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> How I Made Me =N=2.5 MILLION In 7 Days from 2 Common Product I Imported and how you can do the same. Click HERE FOR FREE Details right now Warning To Men: This 3 Foods Is Killing Your Erection. Click Here To Know Them Secret Fruits that increased my Manhood and makes me last 55 minutes+ all time - Click here to get it Warning: Got Arthritis? 3 Simple Ways To Get Cured And Be Permanently Free From Joint Pains. Click Here To See Them REVEALED!! Reduce Your Blood Sugar Level And Reverse Diabetics Within A Short Period Of Time. Click Here To See How MIDNIGHT,Pressed Mr Kilanko Suddenly Couldn't Urinate. Shrink your Enlarged Prostrate Here! Click Here Now