Messi scored both goals, the second coming from a 90th minute spot kick, to earn an undistinguished victory that keeps Barca's title hopes flickering - but it was another tough night for coach Luis Enrique, who was booed by some home fans.
The win leaves Barca second in the table on 51 points, one behind leaders Real, who beat Espanyol 2-0 at the Bernabeu on Saturday.
Real have two games in hand on both Barca and Sevilla, who are third on 49 points after their 2-0 home win over Eibar on Saturday.
Messi, anonymous in the 4-0 Champions League hammering at PSG, put Barca ahead in the fourth minute but Leganes were rewarded for a bold approach which saw them create numerous chances when Unai Lopez levelled in the 71st minute.
Neymar won a penalty late on which Messi converted to steal the win for Barca, keeping them within reach of leaders Real Madrid and temporarily easing the pressure on Luis Enrique.
The coach was jeered by a large number of the home supporters but received roaring approval from the most vocal section.
The coach had made four changes to his side that had been outplayed in Paris, resting Gerard Pique, Jordi Alba, Andres Iniesta and Sergio Busquets.
Yet his side got off to a flying start when Neymar fed Luis Suarez with a through ball into the area and Messi calmly knocked in the Uruguayan's cross.
Leganes, who are three points above the relegation zone in their first season in Spain's top flight, kept their composure and it took a series of fine saves from Barca's Marc-Andre ter Stegen to prevent an equaliser before halftime.
The visitors' equaliser came when there appeared to be little danger as Sergi Roberto went down in his own area under a challenge from Darwin Machis and Miguel Angel Guerrero laid the ball off for Lopez to smash past Ter Stegen.
The goal unleashed a cacophony of boos. Midfielder Andre Gomes was mercilessly whistled off the pitch when he was replaced by Andres Iniesta as the atmosphere turned toxic.
Guerrero came close to snatching a late goal but Ter Stegen repelled his effort while the keeper's team mates struggled to carve open any chances down the other end apart from one Rafinha effort that was blocked.
Yet Neymar kept probing down the left hand side and was rewarded when he was tripped by Martin Mantovani, leaving Messi to avert what would have been a second embarrassment in a week for his coach.
Earlier on Sunday, Italy international Simone Zaza scored his first goal for Valencia as the La Liga strugglers picked up their first win in four games to beat Athletic Bilbao 2-0 and move seven points clear of the relegation zone.
Villarreal won only their second league game of 2017 by winning 1-0 at Real Sociedad, while Celta Vigo thrashed basement club Osasuna 3-0.
Sociedad 0 Villarreal 1
(Nani 13, Zaza 45) Bilbao 0
(Sisto 23, Jozabed 87, Aspas 89) Osasuna 0
(Messi 4, 89-P) Leganes 1
P W D L GD Pts
21 16 4 1 38 52
23 15 6 2 44 51
23 15 4 4 18 49
23 13 6 4 24 45