You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Qt Creator中使用QProcess建立SSH连接失败问题排查

问题分析与解决方案

你的代码核心问题是QProcess::start的调用方式错误:直接传入包含参数的完整命令字符串时,QProcess会将整个字符串视为要执行的程序名称,而非“程序+参数”的组合,导致系统找不到名为ssh -i /home/usr/ssh_key pi@pi_ip_address ls的程序,因此进程启动失败。

另外,你虽然包含了libssh2相关头文件,但当前代码并未使用该库,而是通过调用系统ssh命令实现功能,这部分头文件暂时可以移除(后续若打算改用libssh2直接实现SSH连接再保留即可)。

修复后的代码

void MainWindow::on_connectButton_clicked()
{
    QProcess process;
    // 分离程序与参数:第一个参数是程序名,第二个参数是参数列表
    process.start("ssh", QStringList() << "-i" << "/home/usr/ssh_key" << "pi@pi_ip_address" << "ls");

    if (process.waitForStarted()) {
        QMessageBox::information(this, "Info", "process started");
        // 等待命令执行完成,避免提前读取空输出
        process.waitForFinished();
    } else {
        // 输出具体启动错误信息,辅助排查
        QString errorMsg = QString("process not started: %1").arg(process.errorString());
        QMessageBox::information(this, "Info", errorMsg);
    }

    QString output = process.readAllStandardOutput();
    QString error = process.readAllStandardError();

    if (error.isEmpty()) {
        QMessageBox::information(this, "Command output", output);
    } else {
        QMessageBox::critical(this, "command error", error);
    }
}

额外排查建议

  • 如果仍启动失败,检查ssh程序的完整路径:在终端执行which ssh获取路径,将start的第一个参数替换为该完整路径,比如"/usr/bin/ssh"。
  • 确保私钥文件权限正确:SSH私钥需要设置为仅当前用户可读,在终端执行chmod 600 /home/usr/ssh_key修正权限。
  • 提前在终端手动执行一次该SSH命令,确认没有交互式提示(比如首次连接的主机密钥确认),避免QProcess因等待输入而卡住。

内容的提问来源于stack exchange,提问作者unknown_coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 03:33:08