I've been fighting with Net::SSH2 trying to get it to do simple stuff -- in particular all I needed was for it to be ablet execute commands on the server. I've gotten it all working {the biggest hangup was that, apparently, password auth doesn't work in Net::SSH2 and switching to public_key make things magically work}. Here's the skeleton of a little program that'll execute shell commands:
#!/usr/bin/perl # run shell commands remotely over an SSH connection use strict; use warnings ; use Net::SSH2 ; use constant HOST => "YOURHOST" ; use constant USER => "YOURLOGIN" ; use constant HOSTKEY => "Path to your known_hosts keys file" ; ## To enable the public key login, append your 'pub' key file to the ## authorized_keys file in ~/.ssh on the server use constant PUBLICKEY => "Path to your public key" ; use constant PRIVATEKEY => "path to your private key" ; # Set up the SSH connection my $ssh2 = Net::SSH2->new() ; $ssh2->connect(HOST) or $ssh2->die_with_error ; $ssh2->check_hostkey(tofu => HOSTKEY) or $ssh2->die_with_error ; $ssh2->auth_publickey(USER, PUBLICKEY, PRIVATEKEY) or $ssh2->die_with_error ; $ssh2->auth_ok() ; # Logged in -- now you can execute commands print docmd("cd bin; ls") ; $ssh2->disconnect() ; exit ; # do the command and return the output ## NB: you can only do one command on a channel so we get a channel ## do the command, collect the output and close the channel ## The command must be a fully "punctuated and escaped" shell comman +d. sub docmd { my $chan = $ssh2->channel() or $ssh2->die_with_error ; $chan->exec("($_[0]) 2>&1") ; my $out = ""; while (!$chan->eof) { my $buffer = ""; if (not defined ($chan->read($buffer, 100))) { $ssh2->die_with_error() ; } $out .= $buffer ; } return $out ; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Remote shell via ssh
by hippo (Archbishop) on Aug 15, 2018 at 08:47 UTC | |
by BernieC (Pilgrim) on Aug 15, 2018 at 11:36 UTC | |
by pryrt (Abbot) on Aug 15, 2018 at 14:08 UTC | |
by hippo (Archbishop) on Aug 15, 2018 at 12:42 UTC | |
by VinsWorldcom (Prior) on Aug 15, 2018 at 14:09 UTC | |
|
Re: Remote shell via ssh
by edwyr (Sexton) on Sep 05, 2018 at 15:29 UTC |