Rajeev
Rajeev

Reputation: 46919

Perl ssh operations in one session

In the following code,I am trying to ssh to a different machine and check whether that a file exists or not.
If the file exists, then I need to check whether the person accessing the file is the creator of that file i.e. his username is in the log file.
If present then I need to do remove that file. How can I achieve this with single login i.e, the user will enter his password only once

  $user = $ENV{USER};
  $il_check_cmd = "cat $shared_il_path/$il_name/info/.info_cat.log";
  my $ssh_delete = Net::SSH::Perl->new($hostname, protocol => '1,2', debug => 0, interactive => 1)        ;
  $ssh_delete->login($username, $password);
  ($stdout,$stderr,$exit) = $ssh_delete->cmd("$il_check_cmd");
  if((defined $stderr) && ($stderr =~ /No such file or directory/))
  {
     print "-E- $RUNCMD: \"$il_name\" you have entered does not exist in \"$shared_il_path\"!!        !\n";
     print "-E- $RUNCMD:                        or\n";
     print "-E- $RUNCMD: \"$il_name\" does not contain \".info_cat.log\" file!!!\n";
     print "-E- $RUNCMD: Exiting...\n";
     exit;
  }
  @content = split(/ /,$stdout);
  chomp($user_e = shift(@content));
  if($user_e =~ /\b$user\b/)
  {
            print "This is the user who created the file";
             //then remove the $shared_il_path/$il_name/info/.info_cat.log

   }

Upvotes: 4

Views: 1039

Answers (3)

ikegami
ikegami

Reputation: 385764

my ($stdout, $stderr, $exit) = $ssh->cmd(q{perl -e'
    my ($file_name) = @ARGV;

    ...
    Perl code that does what you want to do
    ...

    if (...some error...) {
       die("...error message...\n");
    }
' filename});

if ($exit) {
    # An error occurred.
    die("Error: $stderr");
}

Just use «'\''» where you would normally use «'».

Upvotes: 1

salva
salva

Reputation: 10244

What's the problem? Just keep sending commands to the remote side through the $ssh_delete object.

And BTW, nowadays, there are better modules for SSH as Net::OpenSSH or Net::SSH2.

Upvotes: 1

Alex Reynolds
Alex Reynolds

Reputation: 96937

Consider using Net::SSH::Expect, instead. The linked page has sample code for an SSH session.

Upvotes: 2

Related Questions