Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

tty Problem while executing command's with sudo over Net::SSH2

by dipesh777 (Novice)
on Dec 07, 2011 at 05:03 UTC ( #942159=perlquestion: print w/replies, xml ) Need Help??
dipesh777 has asked for the wisdom of the Perl Monks concerning the following question:

I am facing a problem while executing commands over ssh. please let me know how can i use/enable tty via Net::SSH2

[root@ip:/tmp] ssh root@ip "sudo -u bob date" root@ip's password: sudo: sorry, you must have a tty to run sudo [root@ip:/tmp] but ssh -t root@ip "sudo -u bob date" solves the problem
How can i do same or enable tty using Net::SSH2 object ?

Sample code which tries to execute command as sudo
use Carp qw(carp confess croak); use Net::SSH2; my $host = "ip"; my $user = "root"; my $pass = "mypassword"; # Connect to host my $ssh = Net::SSH2->new(); if (! $ssh->connect($host)) { print "Failed connection to $host\n"; exit(1); } if ($pass ne "") { if (! $ssh->auth_password($user,$pass)) { print "FAILED SCP password authentication for $username to $host\n"; exit(1); } } else { print "FAILED SCP not the correct credentials provided in config file\ +n"; exit(1); } my $chan = $ssh->channel(); $chan->exec($ARGV[$0]); $stdout = undef; $chan->read( $stdout, 10000 ); $chan->close(); print $stdout; $ssh->disconnect(); exit(0);
perl "sudo -u bob date" won't work perl "date" works and gives the date command output.

Replies are listed 'Best First'.
Re: tty Problem while executing command's with sudo over Net::SSH2
by keszler (Priest) on Dec 07, 2011 at 06:20 UTC

    A little demo for Net::SSH2 Try using the shell method:

    my $chan = $ssh->channel(); $chan->blocking(0); $chan->shell(); print $chan "sudo -u bob date\n"; print "LINE : $_" while <$chan>; $chan->close;

Re: tty Problem while executing command's with sudo over Net::SSH2
by salva (Abbot) on Dec 07, 2011 at 07:50 UTC
    I guess you have to call the pty method on the $chan to get a pseudo tty allocated on the remote side.

    Also, as it seems that you are on a Unix/Linux system, you may like to use Net::OpenSSH instead of Net::SSH2:

    my $ssh = Net::OpenSSH->new($host, user => $user, password => $passwor +d); $ssh->error and die "SSH connection failed: " . $ssh->error; $ssh->system({tty => 1}, $ARGV[0]) or die "remote command failed: ". $ssh->error;

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://942159]
Approved by McDarren
[choroba]: oh, jet2 didn't show in my search as it only flies on Mondays and Fridays
[choroba]: so, now I need to figure out what to talk about at TPCiG
[LanX]: OK ... will you also come to YAPC::EU ?

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (6)
As of 2018-02-23 10:49 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (301 votes). Check out past polls.