简体   繁体   中英

How to send commands in another shell via ssh using python or perl

I need to establish an ssh connection and execute commands remotely, and the flow is: connect by ssh, open a new shell by command line and finally execute the commands.

use Net::SSH::Perl;

my $ssh = Net::SSH::Perl->new('test.com');
$ssh->login('user', 'pass');
my($stdout, $stderr, $exit) = $ssh->cmd('shell');
my($stdout, $stderr, $exit) = $ssh->cmd('ls -l');
print($stdout);

but when you run $ssh->cmd('shell'); it waits, I assume that this opens the shell and since it is a "command" that does not end, it does not pass to the next command which would be to make an ls.

I need to execute commands in the new shell opened by ssh. It is not possible to modify absolutely anything on the remote machine.

Any solution in perl or python will help:)

You don't need to start a new shell explicitly. That's how ssh runs a given command, by passing it as a command line to a new shell.

use Net::SSH::Perl;

my $ssh = Net::SSH::Perl->new('test.com');
$ssh->login('user', 'pass');
my($stdout, $stderr, $exit) = $ssh->cmd('ls -l');
print($stdout);

Perl CPAN recommends to use Net::OpenSSH here instead of Net::SSH::Perl .

Here is the snippet how it should look like:

#!/usr/bin/perl

use strict;
use warnings;

use Net::OpenSSH;

#Function declaration by passing host, user and password as an arguments
my $ssh = ConnectToRemoteMachine ("host_ip_address", "user", "password");

my $result_ls    = $ssh->capture("ls -l");
my $result_shell = $ssh->capture("shell");

print "Result of ls:\n";
print $result_ls."\n";

print "Shell: $result_shell\n"

undef $ssh;
.
.
#Function definition 
sub ConnectToRemoteMachine {
    my ( $host, $user, $passwd ) = @_;
    my $ssh = Net::OpenSSH->new($host,
                                user => $user,
                                password => $passwd);
    $ssh->error and die "Couldn't establish SSH connection: ". $ssh->error;

    return $ssh;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM