josh803316 has asked for the wisdom of the Perl Monks concerning the following question:

I'm attempting to use Net::OpenSSH to connect to a remote linux host and execute a tcpdump command in the background while then executing a ping, stopping the tcpdump and printing the result to the screen. I realize that each command runs in it's own session but I thought I could use nohup and & to create a background process that wouldn't exit. I know that Expect can be used for a more interactive process but I was wondering what the best/recommended way to do this would be (without using Expect).
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use Net::OpenSSH; my $username = 'username'; my $password = 'password'; my $params; my $session_obj; $session_obj = Net::OpenSSH->new("10.2.200.12", user => $username, pas +sword => $password, strict_mode => 0,master_opts => [ -o => "StrictHo +stKeyChecking=no"]); $session_obj->error and die "ssh failed: " . $session_obj->error; print Dumper($session_obj); # Each command runs in its own session my ($out,$err) = $session_obj->capture2('nohup /usr/sbin/tcpdump -i et +h1 -s 1500 -w /tmp/tmp.pcap &'); print "THE OUT IS $out\nTHE ERROR IS $err\n"; ($out,$err) = $session_obj->capture2('ping -I eth1 -c 3 192.168.107.25 +4'); print "THE OUT IS $out\nTHE ERROR IS $err\n"; ($out,$err) = $session_obj->capture2('killall tcpdump'); print "THE OUT IS $out\nTHE ERROR IS $err\n"; ($out,$err) = $session_obj->capture2('tcpdump -r /tmp/tmp.pcap'); print "THE OUT IS $out\nTHE ERROR IS $err\n";

Replies are listed 'Best First'.
Re: Net::OpenSSH and background process
by josh803316 (Beadle) on Aug 24, 2010 at 15:31 UTC
    If I change the command to this:
    nohup /usr/sbin/tcpdump -i eth1 -s 1500 -w /tmp/tmp.pcap </dev/null >> +myLogFile 2>>myErrorFile&
    The background tcpdump process works and stays alive. I'm assuming this is more easily done with a combination of open_ex options just not sure what they should be or if my thought process is correct...
      nohup only does its redirection magic when stdin/stdout/stderr are connected to a tty, that's why you need to explicitly redirect these streams.

      Besides that, you can use Net::OpenSSH spawn method to launch the command in the background:

      # this code does not check for errors! my $pid = $ssh->spawn('/usr/sbin/tcpdump -i eth1 -s 1500 -w /tmp/tmp.p +cap'); ($out,$err) = $ssh->capture2('ping -I eth1 -c 3 192.168.107.254'); $ssh->system('killall tcpdump'); waitpid($pid, 0); ($out,$err) = $ssh->capture2('tcpdump -r /tmp/tmp.pcap'); print "THE OUT IS $out\nTHE ERROR IS $err\n";
        Thank you for the info and helpful example. I was able to get it working both ways with both spawn and the nohup as you suggested. I sincerely appreciate the help!!!