connect to a remote host in perl and run ssh commands as a root user

75 Views Asked by At

I am trying to connect to a remote host as a user. Now i want to run a few commands that need sudo access. The commands are:

export http_proxy=http://xxxx.xx.xx.com:8080
export https_proxy=http://xxxx-xxxx.xx.xx.com:8080
sudo /etc/init.d/filebeat restart
sudo tail -f /var/log/filebeat/filebeat

I tried executing this using

my $ssh = Net::OpenSSH->new("$username\@$Hostname", password => $pass);
my @cmdF = "/etc/init.d/filebeat restart";
print "Restarting filebeat for $webHosts[$i]";
my @cmdF = "/etc/init.d/filebeat restart";
my $outputF = $ssh->capture({stdin_data=>"$pass\n"}, 'sudo', '-Sk', '-p', '', '-', @cmdF);
print "\nCurrent Filebeat Status : $outputF\n\n";

I took just one command at the moment but ended up getting this error:

sudo: /etc/init.d/filebeat restart: command not found

Please help me with the same for all commands..

Thank you in advance.

1

There are 1 best solutions below

4
ikegami On

sudo /etc/init.d/filebeat restart consists of three arguments (including the command):

  1. sudo
  2. /etc/init.d/filebeat
  3. restart

You execute these instead:

  1. sudo
  2. -Sk
  3. -p
  4. Empty string
  5. -
  6. /etc/init.d/filebeat restart

Most relevant is that you combined two arguments into one, producing garbage.

What you need:

my $commands = <<'.';
export http_proxy=http://xxxx.xx.xx.com:8080
export https_proxy=http://xxxx-xxxx.xx.xx.com:8080
sudo /etc/init.d/filebeat restart
sudo tail -f /var/log/filebeat/filebeat
.

$ssh->capture( 'sh', '-c', $commands );