简体   繁体   中英

perl ssh then read file on remote server

I need to

  1. connect to a remote server; then
  2. do some things, like open and read the contents of a file.

For step 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";

yields msg on terminal

Connection established.

so I presume I am ssh connected to remote server, via the code.

For step 2, how do i open and read a file on the remote server using code from the local server? this is the best i can do so far:

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);

yet, it does not add anything to existing file f09.txt ; also if i delete the file, the open does not create it. no errors, but this does not seem to contact the remote file.

just a simple explanation of ssh, then read from remote file would be helpful. other examples i see aren't cutting it. of course, could be me, long day, gotta walk away from it for a while. your time is very much appreciated!

You are essentially trying to modify a file that exists on another machine over SSH. File operations functions cannot handle that.

Is it possible for you to download the file from the other server, update on your local and re-upload the file?

You may also want to experiment with the ssh command:

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: $?"

For performing interesting things over an SSH connection to another machine, you might like to try IPC::PerlSSH . From one of its examples:

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

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