Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain stateful ssh shell session programmatically?

Tags:

ssh

openssh

perl

I am working on an application that needs to send commands to remote servers. Sending commands is easy enough with the plethora of SSH client libraries.

However, I would like shell state (i.e. current working directory, environment variables, etc) preserved between each command. All client libraries that I have seen do not do this. For example, the following is an example of code that does not do what I want:

use Net::SSH::Perl;
my $server = Net::SSH::Perl->new($host);
$server->login($user, $pass);

$server->cmd('cd /var');
$server->cmd('pwd');      # I _would like_ this to output /var

There will be other tasks performed between sending commands, so combining the commands like $server->cmd('cd /var; pwd') is not acceptable.

like image 230
Josh Avatar asked Jul 20 '11 19:07

Josh


1 Answers

Net::SSH::Expect does what you want, though the "Expect" way is not completely reliable as it will be parsing the output of your commands and trying to detect when the shell prompt appears again.

like image 121
salva Avatar answered Oct 02 '22 05:10

salva