开发者

NET::SSH2 with sudo

I'm trying to run various commands with net:ssh2 however the commands need to be run as root. I have root logins disabl开发者_C百科ed over SSH and I have keys setup, so I can ssh and use 'sudo su - root' to get root access without a password. The problem is that I need to run multiple commands so I was wondering if it's possible to connect, then sudo to root, then run all the commands I need without having to pipe an echo to sudo or use expect.

The relevant section of my code I'm working with is the following, I'd preferably like to sudo before the exec($commands[0]) if possible.

EDIT: I can't login directly to root with or without a password as it's against policy unfortunately. I have to connect with my user first.

    my $ssh2 = Net::SSH2->new();
    $ssh2->connect($server) or die "$!\n";
    if ($ssh2->auth_publickey($user,"/home/$user/.ssh/id_rsa.pub", "/home/$user/.ssh/id_rsa"))
    {
            my $chan = $ssh2->channel();
            $chan->blocking(1);
            $chan->exec($commands[0]);
            my @users;
            while(<$chan>) {push(@users,$_);}
            my $stdout=join("",@users);
            print $stdout;
    }


I didn't try this, but su has the -c argument, which passes a single command to the shell to execute, and then finishes the shell. This most likely corresponds to the -c argument of your shell, which in fact happily accepts compound commands here, e.g. a list of commands separated by ;.

Thus executing

sudo su -c 'command1 ; command2 ; command3 ' - root

could work here. (Or even only one of those commands, and then repeatedly call these.)

(But I think there might be something wrong with the settings if they allow a passwordless sudo su - root, but not normal sudo command executing.)


Instead of using sudo su - just proceed each command with sudo. If you are allowed to sudo without a password it should work just fine:

$chan->exec("sudo $commands[0]");

If your command needs root's path just specify the full path to it. (Can't tell since you aren't showing what the command is.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜