Here is the command you specified:
ssh -i $KEY $USER@$HOST "sudo su tom; echo $DATA >> /home/user/file.txt
A couple minor notes about this:
$HOST contain spaces, the command will produce unexpected behavior. (Unlikely.)
$DATA is expanded on the host you are running the
ssh command on, not on the host you are logging into remotely. (I'll assume this is what you intended.)
- You are missing a closing
" at the end of your command. I'll assume this is a copy-paste error.
Now the big point about this command, and the one that solves your problem:
sudo isn't just for running commands as
root. It is for, and I quote the man page:
sudo, sudoedit - execute a command as another user
So, the simple command you want is:
ssh -i $KEY $USER@$HOST "sudo -u tom echo $DATA >> /home/user/file.txt"
This assumes that
$USER has permissions to write to
/home/user/file.txt. If it's only
tom who has those permissions, then use:
ssh -i $KEY $USER@$HOST "sudo -u tom -i 'echo $DATA >> /home/user/file.txt'"
For more, read up on