【发布时间】:2020-06-23 15:53:12
【问题描述】:
我开发了一个脚本,它应该登录到远程服务器并进行某些操作。
在远程服务器中,它会检查sample_file.txt 文件是否存在,如果是,那么它应该在home 路径中创建带有特定数据集的create_user_file.txt 文件。
这里的事情是我可以通过下面的脚本对远程机器执行 ssh,但无法检查文件,因为我不知道如何打开远程会话并执行所有操作。
下面是我的代码:
#!/usr/bin/perl
use Net::OpenSSH;
.
.
.
foreach my $ip( @list_of_ips){
print "Connecting to $ip...\n";
my $ssh = OpenSSH_Connection( $ip, $user, $passwd );
print "Connected!\n";
$dir = "/remote/server/home/path/";
$file = $dir."sample_file.txt";
if (-e $file){ #if sample_file.txt exists then create user file
open(my $fh, '>', $dir."create_user_file.txt") || die "Couldn't open file $!";;
print $fh "ID=123&PW=Passw0rd";
close $fh;
}
last if($ssh); #if connection is success no need to login into another server
$ssh->close();
}
sub OpenSSH_Connection {
my ( $host, $user, $passwd ) = @_;
my $ssh = Net::OpenSSH->new("$user:$passwd\@$host");
$ssh->error and die "Couldn't establish SSH connection: ". $ssh->error;
return $ssh;
}
这里的代码,下面的部分代码应该在远程服务器上执行。但它一直在检查我正在执行此脚本的文件。
if (-e $file){ #if sample_file.txt exists then create user file
open(my $fh, '>', $dir."create_user_file.txt") || die "Couldn't open file $!";;
print $fh "ID=123&PW=Passw0rd";
close $fh;
}
我怎样才能保持打开服务器的远程会话并执行上面的代码,或者我们是否有任何 Perl 模块可以从本地服务器执行这种操作。 TIA。
【问题讨论】:
-
您根本没有使用
$ssh对象。您正在 本地 机器上评估-e,而不是在远程机器上运行命令 -
$ssh->system和$ssh->capture可用于在远程机器上执行 shell 命令。例如,它可以是 Perl 单行代码。 -
我不明白这个问题? shell 命令必须遵守正在使用的 shell 的语法(可能是 bourne shell)。如果该命令执行 Perl 程序,则提供的 Perl 程序必须遵守 Perl 程序的语法。
-
你可以使用 SFTP 吗?可能比与远程 shell 交互更容易。
-
正如@truth 所说,为此使用SFTP,Net::OpenSSH 确实通过Net::SFTP::Foreign 支持它:
$ssh->sftp->test_e($path)