我可以将SSH vi代码编辑器与phpseclib一起使用吗?

时间:2018-11-16 16:28:12

标签: php ssh vi phpseclib

嘿,我想知道在与phpseclibs SSH2连接时是否可以使用vi代码编辑器。我的目标是能够运行PHP脚本并更新配置文件的值。我可以通过SSH正常连接,但是我进入脚本后的所有内容都没有改变目标配置文件中的任何内容。
这就是我到目前为止所拥有的。

<?php
require __DIR__ . '/vendor/autoload.php';
use phpseclib\Net\SSH2;

//simulate pressing the escape key
$esc = chr(27);

$ssh = new SSH2('ip address');
if(!ssh->login('username', 'password')){
    exit('Login Failed');
}

sleep(5);
//enter vi editor
$ssh->write("vi file address\n");
sleep(5);
//"/"enables seach mode in vi editor
$ssh->write("/seachword\n");
sleep(1);
//clears line in vi editor
$ssh->write("cc");
sleep(1);
//enter in new word on that empty line
$ssh->write("replacement word");
sleep(1);
//simulates pressing the esc key
$ssh->write("$esc");
sleep(1);
//saves and closes the vi editor
$ssh->write(":wq\n");
?>

2 个答案:

答案 0 :(得分:1)

我最终使用sed来编辑配置文件,这很好用,感谢neubert。这就是我正在使用的。

$ssh = new SSH2('IP');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

$ssh->exec("sed -i -e 's/text to find/replacement text/g' /path/and/name");

答案 1 :(得分:0)

您确实可以将vi与phpseclib一起使用,但我真的建议您反对它。对于可编写脚本的内容,最好使用sedawk

也就是说,这仍然是可能的,如下所示:

function waitForVertical($ssh)
{
    $output = $ssh->read(
        '#' .
            "\x1B\[\d+C" . // move cursor right n lines
            "(?:All|Top|\d\d%|Bot)" .
            "\x1B\[\d+;\d+H" . // move cursor to screen location v,h
        '#',
        SSH2::READ_REGEX
    );
    if ($ssh->isTimeout()) {
        throw new \Exception('Timeout');
    }
}

function waitForHorizontal($ssh)
{
    $output = $ssh->read(
        '#' .
            "\x1B\[\d+;\d+H" . // move cursor to screen location v,h
            "\d+" .
            "\x1B\[\d+;\d+H" . // move cursor to screen location v,h
        '#',
        SSH2::READ_REGEX
    );
    if ($ssh->isTimeout()) {
        throw new \Exception('Timeout');
    }
}

$ssh = new SSH2('127.0.0.1', 2222);
if(!$ssh->login('vagrant', 'vagrant')){
    exit('Login Failed');
}

$start = microtime(true);

$ssh->read('vagrant@vagrant:~$');
// enter vi editor
$ssh->write("vi file address\n");
waitForVertical($ssh);
// "/"enables seach mode in vi editor
$ssh->write("/seachword\n");
waitForVertical($ssh);
// clears line in vi editor
$ssh->write('cc');
waitForVertical($ssh);
// enter in new word on that empty line
$ssh->write('replacement word');
waitForHorizontal($ssh);
// hit escape button
$ssh->write("\x1B");
waitForVertical($ssh);
// saves and closes the vi editor
$ssh->write(":wq\n");
$ssh->read('vagrant@vagrant:~$');

$elapsed = microtime(true) - $start;

echo "took $elapsed seconds\n";

请注意,您却不使用sleep。从理论上讲,我认为等待特定的输出比仅sleep更好。当然,即使如此,谁能说vi的所有版本是否都将返回用于以相同顺序构建UI的ANSI转义代码。

此外,奇怪的是,您使用vi打开两个文件,而不是一个...