Softpanorama

May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

SSH via Perl

execute commands on remote machines using ssh Perl HowTo

You can execute commands on remote machines from a Perl script using the Net::SSH::Perl module.

This module allows you to execute a command remotely and receive the STDOUT, STDERR, and exit status of that remote command.

One big advantage of Net::SSH::Perl over other methods is that you can automate the login process, that way you can write fully automated perl scripts, no console interaction is required in order to authenticate in the remote machine.

Example:

#!/usr/bin/perl
 
use Net::SSH::Perl;
 
my $host = "perlhowto.com";
my $user = "user";
my $password = "password";
 
#-- set up a new connection
my $ssh = Net::SSH::Perl->new($host);
#-- authenticate
$ssh->login($user, $pass);
#-- execute the command
my($stdout, $stderr, $exit) = $ssh->cmd("ls -l /home/$user");
 

-- IMPORTANT NOTE!!

Execution of Net::SSH::Perl commands can be quite slow if you don't have the Math::BigInt::GMP module; so be sure that you have that module installed (or install it if you don't) in order to avoid the slowness problem. 


Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

NetOpenSSH - search.cpan.org

This package is implemented around the multiplexing feature found in later versions of OpenSSH. That feature allows reuse of a previous SSH connection for running new commands (I believe that OpenSSH 4.1 is the first one to provide all the required functionality).

When a new Net::OpenSSH object is created, the OpenSSH ssh client is run in master mode, establishing a permanent (actually, for the lifetime of the object) connection to the server.

Then, every time a new operation is requested a new ssh process is started in slave mode, effectively reusing the master SSH connection to send the request to the remote side.

Net::OpenSSH Vs Net::SSH::.* modules

Why should you use Net::OpenSSH instead of any of the other Perl SSH clients available?

Well, this is my (biased) opinion:

Net::SSH::Perl is not well maintained nowadays (update: a new maintainer has stepped in so this situation could change!!!), requires a bunch of modules (some of them very difficult to install) to be acceptably efficient and has an API that is limited in some ways.

Net::SSH2 is much better than Net::SSH::Perl, but not completely stable yet. It can be very difficult to install on some specific operative systems and its API is also limited, in the same way as Net::SSH::Perl.

Using Net::SSH::Expect, in general, is a bad idea. Handling interaction with a shell via Expect in a generic way just can not be reliably done.

Net::SSH is just a wrapper around any SSH binary commands available on the machine. It can be very slow as they establish a new SSH connection for every operation performed.

In comparison, Net::OpenSSH is a pure perl module that doesn't have any mandatory dependencies (obviously, besides requiring OpenSSH binaries).

Net::OpenSSH has a very perlish interface. Most operations are performed in a fashion very similar to that of the Perl builtins and common modules (i.e. IPC::Open2).

It is also very fast. The overhead introduced by launching a new ssh process for every operation is not appreciable (at least on my Linux box). The bottleneck is the latency intrinsic to the protocol, so Net::OpenSSH is probably as fast as an SSH client can be.

Being based on OpenSSH is also an advantage: a proved, stable, secure (to paranoic levels), interoperable and well maintained implementation of the SSH protocol is used.

On the other hand, Net::OpenSSH does not work on Windows, not even under Cygwin.

Net::OpenSSH specifically requires the OpenSSH SSH client (AFAIK, the multiplexing feature is not available from any other SSH client). However, note that it will interact with any server software, not just servers running OpenSSH sshd.

For password authentication, IO::Pty has to be installed. Other modules and binaries are also required to implement specific functionality (for instance Net::SFTP::Foreign, Expect or rsync(1)).

SSH to multiple servers and run commands PatchLog

You need to run a list of commands on a list of servers and record the output of each command.

Solution

Create a perl script using Net::SSH::Perl ( a ssh client written as a perl module ). This script will read a list of commands from a file, a list of servers form another file, will connect to each server, execute each command in in the commands file then go to the next server and do the same.

Installation

Download the script: SSH Batch-0.1 (1.5 KB)
install Net::SSH::Perl

sudo perl -MCPAN -e "install Net::SSH::Perl"

Now you can decompress the script and configure it

tar -xzpf ssh_batch-0.1.tar.gz
cd ssh_batch-0.1

put the commands in commands.txt ( one command per line )
put the servers in servers.txt (one per line ) in this format: user@hostname:port,password

Now you can test the script: run ./ssh_batch.pl and look at the output in log.txt

Thread: Perl (SSH to remote host, Issues the command and close the session without waiting it to finish…)

Hi, Script goes to the remote server and runs a shell script "snap.sh" using Net::SSH::Perl. This shell script takes almost 10mins to end, and my perl program waits until it gets output. I want to run the shell script on the remote sever and the program should close the SSH session without waiting for the script to finishes on the remote server. my $ssh = Net::SSH::Perl->new($host, protocol =>2...

Reply 1: Perl (SSH to remote host, Issues the command and close the session without waiting it to finish…)

Andrew White replied 11 months, 1 week ago

Lookup the nohup command. Here is quick post to get you started . For completeness here is what should work in your case... my $cmd="nohup ./bin/snap.sh &";

Reply 2: Perl (SSH to remote host, Issues the command and close the session without waiting it to finish…)

ephemient replied 11 months, 1 week ago

Untested, but can't you just do what ssh -f does? my $ssh = Net::SSH::Perl->new($host, protocol =>2); $ssh->login($username, $password); defined (my $pid = fork) or die "fork: $!"; if ($pid) { close $ssh->sock; undef $ssh; } else { my $cmd="./bin/snap.sh"; my($stdout, $stderr, $exit) = $ssh->cmd($cmd); POSIX::_exit($exit); }

Reply 3: Perl (SSH to remote host, Issues the command and close the session without waiting it to finish…)

Xomo replied 11 months, 1 week ago

Andrew, I tried this. It is running the cmd in the background on the remote server but the session is not closed..it is still waiting. I guess it had lot to do with NET::SSH::Perl module

Reply 4: Perl (SSH to remote host, Issues the command and close the session without waiting it to finish…)

Andrew White replied 11 months, 1 week ago

You'll still need to logout/exit to end the session. I assumed that was simply omitted from the question.

Reply 5: Perl (SSH to remote host, Issues the command and close the session without waiting it to finish…)

Xomo replied 11 months, 1 week ago

Not working same issue, program does not exits.., waiting to get some status from remote server

Reply 6: Perl (SSH to remote host, Issues the command and close the session without waiting it to finish…)

Xomo replied 11 months, 1 week ago

my($stdout, $stderr, $exit) = $ssh->cmd($cmd); At this command the script stops and wait for the remote command to end....

Reply 7: Perl (SSH to remote host, Issues the command and close the session without waiting it to finish…)

ephemient replied 11 months, 1 week ago

@Xomo: What is your platform? If it's Windows, fork emulation is problematic and could cause that.

Reply 8: Perl (SSH to remote host, Issues the command and close the session without waiting it to finish…)

mob replied 11 months, 1 week ago

To run a background job on a remote host, you also need to dissociate from any controlling ttys on the local machine. Try a command like: my $cmd = "./bin/snap.sh < /dev/null > /dev/null 2>&1 &"; I think using nohup is optional.



Etc

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D


Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to to buy a cup of coffee for authors of this site

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last modified: March 12, 2019