首页 > 解决方案 > Can I use the SSH vi code editor with phpseclib?

问题描述

Hey I am wondering if I can use the vi code editor while connected with phpseclibs SSH2. My goal is to be able to run a PHP script and update values of a config file. I can connect via SSH just fine, but nothing I enter into the script afterwords seems to be changing anything in the targeted config file.
This is what I have so far.

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

标签: phpsshviphpseclib

解决方案


我最终使用 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");

推荐阅读