Question

I have php script in which I used expect for automating login and executing command in a remote machine. This is my php code looks like,

<?php
    ini_set("expect.loguser", "Off");
    $stream = fopen("expect://ssh root@10.3.2.0", "r");
    $cases = array (
        array (0 => "*(yes/no)?", 1 => YESNO),
        array (0 => "*d: ", 1 => PASSWORD),
        array (0 => "*$ ", 1 => SHELL, EXP_EXACT)
    );
    switch (expect_expectl ($stream, $cases)) {
        case YESNO:
            fwrite ($stream, "yes\n");
            break;

        case PASSWORD:
            fwrite ($stream, "myrootpassword\n");
            break;

        case SHELL:
            fwrite ($stream, "top -n 1\n");
            break;

        default:
            die ("Error was occurred while connecting to the remote host!\n");
    }
    while ($line = fgets($stream)) {
        print $line;
    }         
    fclose ($stream);
?>

and I know I have installed expect module for php also.

enter image description here

I have installed expect in my Ubuntu machine also.

enter image description here

But I don't know why this is script is not working. I followed http://www.php.net/manual/en/book.expect.php and http://php.net/manual/en/expect.examples-usage.php for creating my php script file. Please advice me, as I am a beginner in PHP, what modification shall I need to do for working expect in php.

Thanks.

Was it helpful?

Solution

First of all, most servers are configured by default to NOT allow remote root login via ssh.

Secondly, why not use SSH keyfiles to allow passwordless logins? It is WAY more secure than storing your password.

  1. Set up an account (for the case of this example, let's call it "automate") that has passwordless sudo access to the automation command (see the NOPASSWD flag on sudoers)
  2. Use ssh-keygen to configure passwordless access to this account from the remote system
  3. Instead of using expect:// to run the command, simply run the command directly:

    ssh automate@10.1.2.3 sudo theCommand

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top