The gunmen fired at the Jaffar Express in Mach area of Bolan district, 70 km southeast of Quetta, Xinhua reported.
The attackers tried to target the people in the engine section to stop the train but retaliation from the police guards foiled their attempt and saved the engine driver and other staff members.
In the shootout, two people were killed and 23 wounded, including two women.
The injured people were admitted to the civil hospital in Quetta.
The train, which was on its way from Quetta to Rawalpindi, was earlier attacked an hour before the incident. A rocket was fired at the train when it was passing through Kolpur area, but the rocket missed its target and instead hit the railway track.
No group has claimed responsibility for the attack yet.