2014-10-09 120 views
0

我需要perl的SSH远程服务器上读取文件

  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的一个简单的解释,然后从远程文件中读取会有所帮助。我看到的其他例子并没有削减它。当然,可能是我,漫长的一天,得离开它一段时间。你的时间非常感谢!

+0

如果我是你,我会写Perl脚本来完成本地任何事情并通过ssh执行它。 – reinierpost 2014-10-10 10:18:40

回答

0

你基本上试图通过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: $?" 
+0

你知道吗,我看到了另外一个评论,但是我想,“为什么这不是?”/但如果是这样的话,那就是它的原因。最终目标是读取日志文件,对其执行“kill -0”操作,如果T [rue]则某个服务正在运行,如果没有则服务停止并需要重新启动。所以,?在本地下载文件,在它上面做一个“猫”来获得pid,在它上面执行kill -0等等。好吧,如果这能完成工作,那么我会冒险去那里。 *!thx!*为您的答案! [首先 !在*!thx!*不是一个不是,而是一个砰的一声]有一点代码幽默那里;) – dcparham 2014-10-09 22:28:28

+0

gm - 顺便说一句,我只想读取文件,也许对它做只读操作。 *当然* [!]我们可以连接到远程服务器,然后打开并读取文件?只是想再次强调,以防万一它微妙地忽略。如果您有更多想法,请回复。非常感激! – dcparham 2014-10-10 01:24:37

+0

此代码让我进入下一步:[4位不制作代码块]: [CODE] use strict; \t使用警告; \t使用诊断; \t使用警告::寄存器; \t use Net :: SSH :: Perl; \t使用Net :: SSH :: Expect; \t use Math :: BigInt lib =>“Calc,GMP,Pari”; \t my $ remote_filename ='/ var/log/systemlog'; \t my $ remote_host =“server.team.domain.com”; \t my $ cmd =“ssh $ remote_host tail -f $ remote_filename |”; \t \t打开我的$ remote_tail,$ cmd或死“可怕的死亡!”; \t \t while(<$ remote_tail>){ \t \t \t print“Remote:$ _”; \t \t} \t exit(0); [/ CODE] – dcparham 2014-10-10 13:25:15

0

在过去的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