我需要建立一个ssh连接并远程执行命令,流程是:通过ssh连接,通过命令行打开一个新的shell,最后执行命令。
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);但是当您运行$ssh->cmd(' shell ');它等待时,我假设这将打开shell,因为它是一个不会结束的“命令”,所以它不会传递到下一个命令,即生成ls。
我需要在ssh打开的新shell中执行命令。不可能完全修改远程机器上的任何内容。
任何用perl或python编写的解决方案都会有所帮助:)
发布于 2020-07-07 00:18:18
您不需要显式地启动一个新的shell。这就是ssh通过将给定命令作为命令行传递给新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);发布于 2020-07-07 00:24:40
Perl CPAN建议使用Net::OpenSSH here而不是Net::SSH::Perl。
下面是它应该是什么样的代码片段:
#!/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;
}https://stackoverflow.com/questions/62760015
复制相似问题