Irregular Expressions

Apr 30 2010   8:36PM GMT

Automating system tasks with Perl – Part 1



Posted by: Dan O'Connor
net::ssh::expect, perl expect

Bash and sh scripts are great for automating system tasks on the local host.

For remote hosts I preferred to use Perl, you can use Perl to login via ssh or telnet ( great for routers ) and you can also do simple tasks on web sites.

For connecting to remote systems I use Net::SSH:Expect.

Here is a simple connection, from the documentation.

        my $ssh = Net::SSH::Expect->new (
            host => "myserver.com",
            password=> 'pass87word',
            user => 'bnegrao',
            raw_pty => 1
        );

        my $login_output = $ssh->login();
        if ($login_output !~ /Welcome/) {
            die "Login has failed. Login output was $login_output";
        }

This will create a connection object called $ssh then verify that you get a welcome prompt.

Doing interactive operations can be completed with the ‘send’ and ‘waitfor’ subs, again another example.

        $ssh->send("passwd");
        $ssh->waitfor('password:\s*\z', 1) or die "prompt 'password' not found after 1 second";
        $ssh->send("curren_password");
        $ssh->waitfor(':\s*\z', 1) or die "prompt 'New password:' not found";
        $ssh->send("new_password");
        $ssh->waitfor(':\s*\z', 1) or die "prompt 'Confirm new password:' not found";
        $ssh->send("new_password");

Part 2 will get more complicated.

Comment on this Post

Leave a comment: