Search code examples
perlexpect.pm

Get session ID of spawned session using Expect in Perl


I'm using Expect to ssh. I want to know the Session ID of the spawned session. How do I do that?

This is my code:

my $addr = "10.101.10.102";
my $cmd = "ssh username@".$addr;
my $exp = Expect->spawn($cmd) or die "Cannot spawn command\n";

Solution

  • Have you tried using the $exp->pid() method of Expect. the documentation for the Expect module says:

    $object->pid()
    Return pid of $object, if one exists. Initialized filehandles will not have pids (of course).
    

    I have tried this in a simple test to telnet to local host, and do a unix ps command to see the processes and also the $exp->pid() command and they match.

    use strict;
    use Expect;
    my $exp = Expect->spawn("ssh localhost") or die "cannot spawn command\n";
    print `ps -ef | grep -i "ssh localhost\$"` ;
    print "PID of spawned process is: ", $exp->pid(), "\n";
    

    OUTPUT

    providnt  4389  4302  0 09:42 pts/1    00:00:00 ssh localhost
    PID of spawned process is: 4389