【问题标题】:PHP Expect not working properlyPHP Expect 无法正常工作
【发布时间】:2013-07-27 04:49:54
【问题描述】:

我有一个 php 脚本,我在其中使用 expect 来自动登录并在远程机器上执行命令。这是我的php代码的样子,

<?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);
?>

我知道我也为 php 安装了 expect 模块。

我也在我的 Ubuntu 机器上安装了 expect。

但我不知道为什么这是脚本不起作用。我跟着http://www.php.net/manual/en/book.expect.phphttp://php.net/manual/en/expect.examples-usage.php 创建了我的php 脚本文件。请建议我,因为我是PHP的初学者,我需要做哪些修改才能在php中工作。

谢谢。

【问题讨论】:

    标签: php shell expect administration php-extension


    【解决方案1】:

    首先,大多数服务器默认配置为不允许通过 ssh 远程 root 登录。

    其次,为什么不使用 SSH 密钥文件来允许无密码登录?这比存储密码更安全。

    1. 设置一个对自动化命令具有无密码 sudo 访问权限的帐户(在本示例中,我们称之为“automate”)(请参阅sudoers 上的 NOPASSWD 标志)
    2. 使用ssh-keygen 配置从远程系统对该帐户的无密码访问
    3. 不用expect://运行命令,直接运行命令即可:

      ssh automate@10.1.2.3 sudo theCommand

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-15
      • 1970-01-01
      • 2019-01-13
      • 2021-08-16
      • 2012-10-28
      • 2013-10-13
      • 2012-12-06
      • 2016-01-19
      相关资源
      最近更新 更多