user3164754
user3164754

Reputation: 215

sudo to root in middle of script

I have a Perl script running as user1. This script is basically used to stop/start or bounce a process running as user2 on RHEL. Now, the stop/start is working since i am using a warpper of user2 to run the stop/start and bounce commands.

The issue is, this process is a jvm which is usually busy. So, stop/start or bounce wont work all the time if the jvm is really busy. So I am trying to kill the processid using a kill -9 for a quicker bounce.

So, can i do a sudo to user2 or root in the middle of my Perl script running as user1 to kill -9 the process.

I tried using

su - user2 -c `kill -9 pid`;
sudo -u user2 -c `kill -9 pid`;

So my script to stop/start/bounce is running as user1. The process being stopped/started/bounced is running as user2. I want my Perl script to kill the process if stop/start/bounce is taking longer than 30 secs.

Please help.

Upvotes: 2

Views: 498

Answers (1)

Gary Jackson
Gary Jackson

Reputation: 545

If you can't fix your sudoers file with visudo, then the Expect module is an option:

#!/usr/bin/perl

use Expect;

# Get the password when your program starts
my $pw = <>;

# ... do stuff ...

# use the password when you need it
my $exp = Expect->spawn("/usr/bin/sudo", "-k", "-u", "user2", "kill", "-9", $pid);
print("expecting the prompt\n");
$exp->expect(undef, "-re", "Password:", sub { print("prompt matched\n"); $exp->send($pw); exp_continue; });
$exp->soft_close();

Seriously, though, the best thing is to put the appropriate entry in sudoers.

Upvotes: 1

Related Questions