Execute internal script as different user

I have a script that I must run as user X and need to send the results to a different server as user Y (sftp). User Y has been set up to not require password authentication between the 2 servers. I would prefer to keep these in a single script, as our operations might have to run it from time to time and I would prefer to keep things simple.

Another thought was to have 2 scripts that poled a status file to see "whose" turn it was to execute.

Any suggestions?

Thanks

What is supposed to be executed by Y?

as user X

....

sftp ... Y@server <<EOF
.....
EOF

.....

Yes, sftp needs to be run as user Y. The main script is a start/stop process for a web based application (separate app and web servers). All the processes must be started or stopped as user X, but user Y must be used to send results to the other server detailing basically whose turn it is to run.

[app server script]
start environment (x)
start rmi (x)
sftp web (y)
wait till app continue
start scheduler (x)

[web server script]
wait till web
start web (x)
sftp app continue (y)

since everything else is run under user x, maybe you can just enclose the sftp command for user y in an su -c command

I am also trying to keep from storing the password of the User Y on the system as well and user X is not root.

Try this

script starts as X

script then does SSH to other system as Y using private key as follows...

echo this is running as X here
ssh -i identity Y@other <<EOF
echo this script part will run as Y on the other machine
EOF
echo this is back running as X here

Ok. Iwill try that, but we initially had it setup as host-based authentication instead of public key. It is being changed to public key.