Sending key via ssh or using mouse to activate Target Display Mode?
Sorry, John Schmitt, your untested solution doesn't work, but you were on the right track. This one's tested, and it works.
The right command is (if you embed Applescripts in shell scripts, which is how I prefer doing it):
osascript -e 'tell application "System Events" to key code 144 using command down'
Save that, for example, as ~/bin/tdm.sh, on the the target display machine.
Then, from the primary machine, issue this in Terminal:
ssh username@target-display-machine "~/bin/tdm.sh"
There are other ways to save and invoke the Applescript command. I find it more convenient and consistent to embed them in shell scripts -- my particular preference, since I do a lot of shell scripts anyway.
Untested, but I might consider creating an applescript in ~/bin/command_f2 on the iMac with the following contents:
tell application "System Events" to keystroke "F2" using {command down}
and then from your laptop type:
ssh me@imac '~/bin/command_f2'
To get more help with this question, consider changing the title to something like "Sending keystrokes via ssh" because "keys" could mean confused with ssh keys.
Good luck.