Lunar rocks contain a record of an ancient magnetic field that seems to have persisted for more than 400 million years and which has been attributed to a lunar dynamo. Models of conventional dynamos driven by thermal or compositional convection have had difficulty reproducing the existence and apparently long duration of the lunar dynamo. Here we investigate an alternative mechanism of dynamo generation: continuous mechanical stirring arising from the differential motion, due to Earth-driven precession of the lunar spin axis, between the solid silicate mantle and the liquid core beneath. We show that the fluid motions and the power required to drive a dynamo operating continuously for more than one billion years and generating a magnetic field that had an intensity of more than one microtesla 4.2 billion years ago are readily obtained by mechanical stirring. The magnetic field is predicted to decrease with time and to shut off naturally when the Moon recedes far enough from Earth that the dissipated power is insufficient to drive a dynamo; in our nominal model, this occurred at about 48 Earth radii (2.7 billion years ago). Thus, lunar palaeomagnetic measurements may be able to constrain the poorly known early orbital evolution of the Moon. This mechanism may also be applicable to dynamos in other bodies, such as large asteroids.