My Mac prompts to shut down randomly

The most likely cause is your keyboard is failing; specifically there is an issue with your power button where it intermittently causes it to stick.

The shutdown dialog box you are seeing is a result of the power management daemon intercepting the momentary press of the power butting thinking you want to sleep, restart, or shutdown.

First I also taught it was the power off button but in this case It should also shutdown when I'm on target mode but it doesn't

The reason you are not seeing the power button have an effect is because power management must be loaded to intercept the signal. Not only is power management not loaded, nothing of OS X is being loaded either.

Target Disk Mode is a firmware feature, not a feature of OS X. What your Mac is doing is allowing the Firewire/Thunderbolt port to pass an external connection through to the internal drive so what you have is in fact, the most expensive Firewire or Thunderbolt external drive ever made.

Because it hasn't loaded any systems management services, a simple press of the power button isn't going to do anything; try it yourself. However, to turn off your computer in TDM, you have to hold down the power button for 5 seconds - exactly the same way you would if your fully booted OS X Mac would if it stopped responding.

How to Verify...

This is a simple procedure to validate whether or not your power button is failing. Since it's part of the keyboard assembly this requires disconnecting the keyboard and shorting the power pads to power on your logic board. I recommend getting an external mouse/keyboard (USB) because when you disconnect your MBP keyboard, you will need something on which to type.

Once you remove the back cover and disconnect the keyboard/trackpad assembly from the logic board, you will need to turn on the MBP by "shorting" the two power pad connections. Don't worry, this is exactly what a switch does - it shorts the connection. You can use a paperclip, but my preference is to use a flat blade screwdriver wide enough to touch both contacts.

(The images below are from a 2010 MBP, if you give me your specific model, I will update the shots)

2010 Macbook Pro Power Pad Far shot 2010 Macbook Pro Power Pad close up

You won't be able to power on your MBP unless you open the lid, so you will have to gently have it upside down on your desk with the lid open as you perform this procedure. It helps if you put a towel of some sort of padding to protect it. Once it's powered on, just flip it back to its normal position (off the towel); you won't need to put the bottom cover back on. Make sure your mouse and keyboard are connected.

If the problem goes away once you do this, then the problem is your keyboard - it's time for a replacement.