【问题标题】:perl ssh then read file on remote serverperl ssh 然后读取远程服务器上的文件
【发布时间】:2014-12-04 23:15:27
【问题描述】:

我需要

  1. 连接到远程服务器;那么
  2. 做一些事情,比如打开和读取文件的内容。

对于第 1 步:

my $server = "remoteservername.company.com";
my $ssh = Net::SSH::Perl->new("$server", debug => 1, protocol => 2, StrictHostKeyChecking => "no") or die "Error connecting server $server";

在终端输出消息

Connection established.

所以我假设我通过代码 ssh 连接到远程服务器。

对于第 2 步,我如何使用本地服务器的代码打开和读取远程服务器上的文件?这是迄今为止我能做的最好的:

use strict;
use warnings;
use diagnostics;
use warnings::register;
use Net::SSH::Perl;
use Net::SSH::Expect;
use Math::BigInt lib => "Calc,GMP,Pari";

my $server = "server09";
my $ssh = Net::SSH::Perl->new("$server", debug => 1, protocol => 2, StrictHostKeyChecking => "no") or die "Error connecting server $server";

#open(FILE, "/home/myid/f09.txt") || print("Unable to open test.o\n"); #works, on local, opens file[does not fail].

#open(FILE, "server09://home/myid/f09.txt") || print("Unable to open test.o\n");  #---> error: "Unable to open test.o"

my @remote_text = `this text is put into array.`;
my $remote_text = join ('',@remote_text);
open (FILE,'>/home/myid/f09.txt');
print FILE "$remote_text";
close (FILE);

exit(0);

然而,它不会向现有文件f09.txt 添加任何内容;如果我删除文件,open 也不会创建它。没有错误,但这似乎没有联系到远程文件。

只是对 ssh 的简单解释,然后从远程文件中读取会有所帮助。我看到的其他例子并没有削减它。当然,可能是我,漫长的一天,要离开它一段时间。非常感谢您的宝贵时间!

【问题讨论】:

  • 如果我是你,我会编写 Perl 脚本在本地完成所有操作并通过 ssh 执行。

标签: perl ssh


【解决方案1】:

您实际上是在尝试通过 SSH 修改另一台机器上存在的文件。 文件操作函数无法处理。

您是否可以从其他服务器下载文件,在本地更新并重新上传文件?

您可能还想尝试使用 ssh 命令:

my @remote_text = ('this text is put into array.');
my $remote_text = join ('',@remote_text);

my @args = ("ssh server09", "echo '$remote_text' > /home/myid/f09.txt");
system(@args) == 0 or die "system @args failed: $?"

【讨论】:

  • 你知道,我看到了另一个评论,但我想,“为什么不呢?”/但如果是这样,那么它就是这样。最终目标是读取日志文件,对其执行“kill -0”,如果 T[rue] 则某个服务正在运行,否则该服务已停止并需要重新启动。所以,?在本地下载文件,在其上执行“cat”以获取 pid,对其执行 kill -0 等...?好吧,如果这能完成工作,那么我会去那里冒险。 !thx! 为您解答! [首先 !在 !thx! 中不是不是,而是一声巨响] 那里有一点代码幽默 ;)
  • gm - 顺便说一下,我只想读取文件,也许对它进行只读操作。 当然 [!] 我们可以连接到远程服务器,然后打开并读取文件??只是想再次强调这一点,以防万一它微妙到可以忽略。如果您有更多想法,请回复。非常感谢!
  • 这段代码让我进入了下一步:[4 个空格不构成代码块]:[CODE] 使用严格;使用警告;使用诊断;使用警告::注册;使用 Net::SSH::Perl;使用 Net::SSH::Expect;使用 Math::BigInt lib => "Calc,GMP,Pari";我的 $remote_filename = '/var/log/systemlog';我的 $remote_host = "server.team.domain.com";我的 $cmd = "ssh $remote_host tail -f $remote_filename |";打开我的 $remote_tail、$cmd 或死去“可怕的死亡!”;而(){打印“远程:$_”; } 退出(0); [/CODE]
【解决方案2】:

要通过 SSH 连接到另一台机器执行有趣的操作,您可能想尝试IPC::PerlSSH。从它的一个例子:

use IPC::PerlSSH;

my $ips = IPC::PerlSSH->new( Host => "over.there" );

$ips->use_library( "FS", qw( mkdir chmod writefile ) );

$ips->call( "mkdir", "/tmp/testing" );
$ips->call( "chmod", 0600, "/tmp/testing" );

$ips->call( "writefile", "/tmp/testing/secret", <<EOF );
Some secret contents of my file here
EOF

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2020-06-23
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多