While in space or on the moon is it possible to use earth existing magnetic field to generate electricity?
Yes, sort of.
The most basic form of electrical generator consists of a wire moving through an electrical field. In space, this would take the form of an "electrodynamic tether": a wire extended outwards from a spacecraft.
But energy needs to come from somewhere, and with an electrodynamic tether, the energy comes from the spacecraft's orbital motion. This slows the spacecraft down and will eventually cause it to re-enter. A more common proposal for using an electrodynamic tether is to run it in reverse: use a solar panel to run an electric current through the tether, causing it to act as an electric motor. This would let the spacecraft adjust its orbit without needing to use fuel.