【问题标题】:phpseclib ssh2 enable ttyphpseclib ssh2 启用 tty
【发布时间】:2023-03-13 22:39:01
【问题描述】:

我的 ssh 脚本:

include('Net/SSH2.php');
set_include_path(getcwd());



$ssh_host = "myserver.com";
if($ssh_host != null){
    $ssh_user = globals::$ssh_logins[$ssh_host];
    $ssh = new Net_SSH2($ssh_host);
    //$ssh->enablePTY();
    if (!$ssh->login($ssh_user['username'], $ssh_user['password'])) {
        echo $ssh->isConnected() ? 'bad username or password' : 'unable to establish connection';
    }
    echo $ssh->exec('sudo bash /myscript.sh');
}else{
    echo "no host: " . $ssh_host;
}

调用时:

echo $ssh->exec('sudo bash /myscript.sh');

我得到输出:

stdin: is not a tty
sudo: sorry, you must have a tty to run sudo

如何在 phpseclib 上启用 tty? Sudo 是必要的,检索输出也很重要。我的脚本返回多行。

  • Centos 7
  • PHP 7

有趣的链接:https://unix.stackexchange.com/questions/136676/sudo-sorry-you-must-have-a-tty-to-run-sudo-when-using-sudo-in-a-remote-scrip?newreg=f31852b195804fd1b988aeb0a9ce59d9

【问题讨论】:

标签: php linux phpseclib


【解决方案1】:

您的$ssh->enablePTY() 走在正确的轨道上,但是一旦您这样做了,您就需要使用$ssh->read()。没有 PTY $ssh->exec() 将返回命令输出。如果您执行$ssh->enablePTY(),则需要执行$ssh->read() 才能获得输出。

这样做的原因是,使用 PTY 可以将数据发送到 shell 和从 shell 发送,而没有 PTY 则不能。没有 PTY,你得到的输出就是你得到的输出,没有输入可以改变它,因为你不能发送输入。用 PTY 输入可以改变输出。

同样相关的是,phpseclib 的文档谈到了用它来做sudo。来自http://phpseclib.sourceforge.net/ssh/examples.html#sudo

<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

echo $ssh->read('username@username:~$');
$ssh->write("sudo ls -la\n");
$output = $ssh->read('#[pP]assword[^:]*:|username@username:~\$#', NET_SSH2_READ_REGEX);
echo $output;
if (preg_match('#[pP]assword[^:]*:#', $output)) {
    $ssh->write("password\n");
    echo $ssh->read('username@username:~$');
}

如果您的帐户没有密码,我想这没关系,但如果您有密码,那么您需要执行上述操作。

【讨论】:

    猜你喜欢
    • 2020-10-22
    • 2018-01-29
    • 1970-01-01
    • 2012-08-27
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多