Real lost 2-1 in the second leg at their Bernabeu home as the tie finished 2-2 on aggregate with their modest city neighbours going through on away goals despite having lost the first leg 1-0 last week.
Javi Eraso gave Leganes a 32nd minute lead before Karim Benzema levelled after 47 minutes but Brazilian striker Gabriel Pires then hit the winner with a firm header eight minutes later.
The fans let their feelings known by booing off the team at half-time.
Leganes have a budget of just 45 million euros -- six times less than the 675 million euros commanded by mighty Real.
More From This Section
Even without Cristiano Ronaldo and Gareth Bale, who were rested Wednesday after starring in the 7-1 rout of Deportivo La Coruna at the weekend, Real's second-string side should still have had enough firepower for a side languishing in 13th spot in La Liga.
In the night's other game, Valencia made the semi-finals but needed a 3-2 penalty shoot-out to defeat Alaves who won 2 -1 for a 3-3 aggregate.
On Tuesday, Sergio Escudero's goal after just 24 seconds set Sevilla on their way to a 3-1 win over Atletico Madrid and a place in the semi-finals. Sevilla, finalists in 2016, had won the first leg 2-1.
Meanwhile, Brazilian playmaker Philippe Coutinho has been named in the Barcelona squad for Thursday's Copa del Rey clash against Espanyol, his first call-up since his 160 million euros ($194 million, 142 million) move from Liverpool.
The 14 shirt was alao worn by the club's Dutch legend Johan Cruyff who died in 2016.
Coutinho has been cleared to make his debut at Camp Nou as Barcelona look to overturn a 1-0 defeat to Espanyol in the first leg of their quarter-final clash.
Coutinho spent six months with Barcelona's city rivals on loan in 2012.
Club captain Andres Iniesta and striker Paco Alcacer were also included in the 19-man squad for Thursday's game as was Colombian defender Yerry Mina, antother transfer window recruit.