【问题标题】:Using ssh in cy.exe() always get timeout error在 cy.exe() 中使用 ssh 总是出现超时错误
【发布时间】:2026-01-30 02:00:02
【问题描述】:

我在 cypress exec 命令中使用 ssh 命令。 ssh 命令正常工作,但我总是从 exec() 函数中得到超时错误。

代码为:cy.exec('ssh username@111.111.1.1 "\file.exe"')

实际上这段代码工作正常,我可以看到 file.exe 在远程桌面上工作,但我在 exec() 上得到错误。

我想我必须在 ssh 命令中添加一些选项,例如 -q -w 。我尝试了其中一些,但没有成功。

你能帮帮我吗?

【问题讨论】:

  • ssh 给你什么退出代码?或许{ failOnNonZeroExit: false }cy.exec() 可以解决问题。 docs.cypress.io/api/commands/…
  • 我试过 failOnNonZeroExit 这个。它不起作用。

标签: ssh exec cypress


【解决方案1】:

也许 exec 在与被调用命令交互的方式上太有限了,你需要一个可编程的 API 而不仅仅是配置选项。

您可以尝试使用任务,有一个库 node-ssh 将与赛普拉斯任务交互。

我不熟悉 ssh 协议,因此您必须填写这些详细信息,但这里是 Cypress 任务和 node-ssh 库的基本示例

cypress/plugins/index.js

module.exports = (on, config) => {
  on('task', {
    ssh(params) {  

      const {username, host, remoteCommand} = params // destructure the argument

      const {NodeSSH} = require('node-ssh')
      const ssh = new NodeSSH()

      ssh.connect({
        host: host,
        username: username,
        privateKey: '/home/steel/.ssh/id_rsa'  // maybe parameterize this also
      })
      .then(function() {

        ssh.execCommand(remoteCommand, { cwd:'/var/www' })  
           .then(function(result) {
             console.log('STDOUT: ' + result.stdout)
             console.log('STDERR: ' + result.stderr)
           })
      })

      return null   
    },
  })
}

返回结果

以上 ssh 代码仅来自 node-ssh 的示例页面。如果你想返回result 的值,我想这样就可以了。

module.exports = (on, config) => {
  on('task', {
    ssh(params) { 
 
      const {username, host, remoteCommand} = params // destructure the argument

      // returning promise, which is awaited by Cypress
      return new Promise((resolve, reject) => {

        const {NodeSSH} = require('node-ssh')
        const ssh = new NodeSSH()

        ssh.connect({   
          host: host,
          username: username,
          privateKey: '/home/steel/.ssh/id_rsa'
        })
        .then(function() {

          ssh.execCommand(remoteCommand, { cwd:'/var/www' })
            .then(function(result) {
              resolve(result)          // resolve to command result
            })
        })
      })
    },
  })
}

测试中

cy.task('ssh', {username: 'username', host: '111.111.1.1', command: '\file.exe'})
  .then(result => {
    ...
  })

一个任务只允许一个参数,所以传入一个对象并在任务内部对其进行解构,如上所示。

【讨论】:

  • 好的,我会尝试你给我的代码但是我在我的测试集上多次使用 exec() 函数。 ssh user@111.111.1.1 taskkill /f /im "file.exe" 我这样用。而且我没有收到错误。它工作正常。但是当我尝试运行文件时,我没有得到响应。就在一分钟前,我尝试使用以下启动命令: cy.exec('ssh username@111.111.1.1 start "\file.exe"') 但我没有收到超时错误。但file.exe 没有启动。真的很有趣
  • 是的,很有趣。您可以使用 Cypress 外部的简单节点脚本微调 node-ssh 代码,然后在正确且一致地运行后,将脚本代码添加到任务中。
  • 我建议在任务中保留return new Promise((resolve, reject) => { 行,因为它可以更轻松地等待 ssh 调用完成(即使您不需要 result)。 cy.exec() 应该等待和阻塞,但这取决于被调用的代码如何表示进程结束。这可能就是为什么 cy.exec() 有时有效,有时无效。
最近更新 更多