Rahul Gupta has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I am connecting linux box from Windows 7 machine using Net:ssh2 module but switch user command are not working.

Here is my code

use warnings; use strict; use Net::SSH2; use Net::SSH2::Expect; my $ssh2 = Net::SSH2->new(); $ssh2->connect('192.168.XX.XXX') or die "Unable to connect Host $@ \n" +; #this works for passwords $ssh2->auth_password('root','root') or die "Unable to login $@ \n"; my @array = ('whoami','su root', 'whoami'); foreach (@array){ my $chan = $ssh2->channel(); $chan->exec($_); my $buflen = 3000; my $buf1 = '0' x $buflen; $chan->read($buf1, $buflen); print "CMD1:\n", $buf1,"\n"; }

Please help me to resolve this problem
Thanks in advance

Replies are listed 'Best First'.
Re: Switch user command not working user Net:SSH2 module
by salva (Canon) on Oct 29, 2013 at 09:21 UTC
    Net::SSH2 runs every command in a different shell session. Read the FAQ entry "Can't change working directory" from the Net::OpenSSH docs for a more detailed explanation.

    There are two ways to do what you want:

    One is to start a shell on the remote shell and then simulate an interactive dialogue with it (usually, you use Expect for that, though Expect doesn't work on Windows*). This is hard and error prone, as you will have to look into the command output for the prompt in order to detect when some command is done.

    The other way is to combine the sequence of commands into a single one. But, su usually asks for the password and so you will have to send it through its tty.

    su root -c "whoami"

    An easier way is to use sudo, that can be configured to not ask for a password, or alternatively, in recent versions, to get the passwords from stdin. For instance, using Net::SSH::Any:

    my $ssh2 = Net::SSH::Any->new('192.168.XX.XXX, user => 'root', passwor +d => 'root'); print $ssh2->capture({stdin_data => "$sudo_passwd\n"}, 'sudo', '-Sk', '-U', $user, '-p', '', '--', 'whoami');

    *) unless you use the perl from Cygwin.

Re: Switch user command not working user Net:SSH2 module
by hdb (Monsignor) on Oct 29, 2013 at 08:20 UTC

    And what exactly happens? You log in as root on the linux box via ssh, the first whoami should return root, su root should execute without asking for a password, you will still be root, so the second whoami should return root as well.

    It would be helpful if you provided some details how your script deviates from this sequence of events.