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 开发者_如何学Pythonscript 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);
$ssh->login($username, $password);
my $cmd="./bin/snap.sh";
my($stdout, $stderr, $exit) = $ssh->cmd($cmd);
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 &";
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);
}
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.
I use Net::OpenSSH for this. It has a spawn method that does exactly what you're looking for.
my %conn = map { $_ => Net::OpenSSH->new($_) } @hosts;
my @pid;
for my $host (@hosts) {
open my($fh), '>', "/tmp/out-$host.txt"
or die "unable to create file: $!";
push @pid, $conn{$host}->spawn({stdout_fh => $fh}, $cmd);
}
waitpid($_, 0) for @pid;
精彩评论