Madrid, beaten 2-0 at home by Real Sociedad in LaLiga on Sunday, were again unconvincing for large periods of Wednesday's match at the Santiago Bernabeu but pulled through after the break.
Captain Ramos gave them the lead shortly before half-time with a penalty, taking his tally for club and country to three figures after Alvaro Odriozola was fouled by Gerard Gumbau.
With Leganes tiring in the second period, Lucas Vazquez capitalised on a defensive mistake before Vinicius Junior cushioned in a low volley to put Madrid in a strong position ahead of the second leg.
Madrid had the first good chance in the 15th minute but Karim Benzema could not get enough power on a header from Odriozola's cross to trouble Ivan Cuellar, the striker then rifling over when found by Vazquez.
Martin Braithwaite headed a corner straight at Keylor Navas, deputising for injured Thibaut Courtois, and the striker failed to hit the target with another good chance soon after.
Braithwaite was proving a handful and the Dane, making his debut after joining on loan from Middlesbrough, forced a fine save from Navas after beating Benzema to Nabil El Zhar's cross.
But Madrid took the lead from the spot in the 44th minute, Ramos converting a penalty awarded when Gumbau clumsily felled Odriozola as the full-back ran into the box.
Vazquez doubled the hosts' lead in the 68th minute. Benzema's pressing won the ball back deep in Leganes' territory after Unai Bustinza's poor pass, with Vinicius unselfishly squaring for Vazquez to tuck the ball home.
Vinicius completed the scoring with 13 minutes remaining, beautifully finishing an Odriozola cross to net for his second consecutive appearance in the Copa del Rey.
Madrid flirt with another shock
Last season, Leganes dumped Madrid out of the Copa del Rey with a 2-1 win at the Bernabeu, reaching the semi-finals for the first time in their history. Madrid can count themselves fortunate their two goals in the second half have effectively ended the tie early as they did not impress.
Vinicius a talent to watch
A goal and an assist was a fine return for Vinicius, who will play a key role in the post-Cristiano Ronaldo era at Madrid. The 18-year-old was his side's brightest performer, earning a high five from Santiago Solari when he was substituted immediately after his goal, Brahim Diaz coming on for his debut following his move from Manchester City.
Benzema's struggle for form continues
With Isco and Luka Modric benched, Madrid's supply line to Benzema was lacking. The former France forward, who looks low on confidence, could and perhaps should have scored a pair of early goals, but he did at least help to create his side's second.