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

I'm trying to write a magic script that will execute a command (for example, ssh) and monitor user input. If it sees "@@" it will accept the rest of the input up the <RETURN> as the filename of a script. For instance, after entering "@@test", a single <RETURN> is entered and the script, "test" begins to execute. Every output of "test" script goes to the "ssh" command as if the original person had typed them in. It runs until the owner kills it. Here's what I have:
if ($input[0] eq "ssh"){ # SSH session my $exp = new Expect; $exp->raw_pty(1); $exp = Expect->spawn("$cmd\r"); $exp->expect(1, '-ex', "$_"); system("stty -echo"); $exp->expect (1, '-ex', "$_"); $password = <STDIN>; system("stty echo"); chomp $password; $exp->send ("$password\r"); $exp->expect (1, '-ex', "$login[1]:~#"); my $input = <STDIN>; chomp $input; if ($input =~ "@@"){ $input =~ s/@@//; my $script = "/root/Desktop/$input"; open(SCRIPT, "./$input|"); while (<SCRIPT>){ $exp->send ("$_\r"); } close (SCRIPT); } else {$exp->send ("$input\r");} } else{ # Telnet session my $exp = new Expect; $exp->raw_pty(1); $exp = Expect->spawn("$cmd\r"); $exp->expect(1, '-ex', "Password:"); system("stty -echo"); $password = <STDIN>; chomp $password; $exp->send ("$password\r"); system("stty echo"); $exp->expect(1, '-ex', "$_"); # User mode $command = <STDIN>; chomp $command; $exp->send ("$command\r"); $exp->expect (1, '-ex', "$_"); # Privileged mode system("stty -echo"); $password = <STDIN>; chomp $password; system("stty echo"); $exp->send( "$password\r"); $exp->expect (1, '-ex', "$_"); my $input = <STDIN>; chomp $input; if ($input =~ "@@"){ $input =~ s/@@//; my $script = "/$dir/$input"; open(SCRIPT, "./$input|"); while (<SCRIPT>){ $exp->send ("$_\r"); } else {$exp->send ("$input\r");} }
When I telnet, it will read “test” and execute the commands. But when I ssh, for some reason it does execute the commands. Any help is greatly appreciated, I’m not really sure how this “magic” thing works.

Replies are listed 'Best First'.
Re: Help Using Magic Script
by choroba (Cardinal) on Jun 07, 2010 at 15:43 UTC
    There are many identical lines in your code. Consider using a sub with a parameter telling it to use either telnet or ssh. (See Copy and paste programming)
Re: Help Using Magic Script
by Anonymous Monk on Jun 07, 2010 at 15:40 UTC
    Correction: When I use ssh, it DOES NOT execute the commands.