Perl script remote execution as another user

Hi gurus,

I have a requirement where I need to remotely run a perl script as another user.
Running the script locally as the required user is fine, however I need to su with the script due to filesystem permission issues. I do not want to update permissions on the remote server due to security reasons.

I need this to monitor a database instance via nagios, so need to run the check on the remote server as an oracle related user. I've set up the sudo rules on the remote server so that everything works when the check is run as an oracle user, however the check doesn't work when run from the monitoring server.

How do I su/sudo within a perl script so that all subsequent lines are executed as a different user?

This is my script..

what am I doing wrong? How can I execute the entire script as another user on a remote host?

How are you running this script on the remote host?

Do you really need to su in the script? You realize that only things run by su get user permissions, it doesn't promote the process that ran su?

Ideally you'd want to login as the user then run perl. You could do:

ssh -t username@host perl < perl.pl

I need to initially ssh as a specific user and then run the perl script as another user. This is due to the monitoring software we use.

su has to run your perl program, not vice versa. su doesn't change the login of existing programs. su creates a new login under a different user which does what you tell it to.

ssh username@host su -c "/usr/bin/perl" - othername < localfile.pl

I understand how su & sudo work.

My requirement is to be able to switch users from within the perl script, so that specific actions/commands are performed under the required account. I do not want to ssh as the required user. I need to make the connection to the box as a specific user and then run the script (or parts of it) as a different user.

I do not want to use a wrapper script or any other external method, surely there must be a way to switch users from within the script itself. I will have a subsequent requirement where I want to switch to different users multiple times so I want to be able to do it only from within the script itself.

Thanks

That's exactly what my suggestion does...

Only root can actually switch users. And even then, you can't do it unless you custom-compile your own nonstandard perl.

If you want your code to operate in standard perl, within sane safety bounds, and without weird convolutions, you'll have to actually use the system as designed. One process, one user.

So, creating processes inside perl like su -c perl username and feeding perl statements into the stdin of that process would be one way to go.