Skip to content

can i set timeout for ssh command? #465

Closed

Description

@sga8

helllo.
i like node-ssh and i am using this library in our project.

I have a question about timeout.
when i use "execCommand" or "exec", how to set timeout ?

if i want to wait just 5 sec, how to set ?

Activity

  1. zydingjun commented on Jul 27, 2023

    @zydingjun

    these demo may help you:

    let timerID = setTimeout(()=>{
        console.log('sorry the timeout')
    }, 5000)
    
    ssh.execCommand('echo hello', {cwd:'/'}).then((result) => {
        console.log('nice, we got peer command output' + result.stdout)
    }) .catch((err) => {
        console.log('something error')
    }).finally(() => {
       clearTimeout(timerID)
       timerID = null
    })

    Edit by @steelbrain: Added formatting

  2. steelbrain commented on Aug 7, 2023

    @steelbrain
    Owner

    Hi @sga8!

    Thanks for writing in. Since this library is a wrapper around the ssh2 package, it supports the same features.

    If you are using the exec or execCommand functions, it's not possible (as per my current knowledge) to issue an abort command. But depending on your usecase, you should be able to use the requestShell function, and invoke the command in the shell. Inside the shell, you can send various signals like ctrl-c through stdin.

    If the commands you are executing are non consequential, you can do what @zydingjun recommended above and have a timeout in your local code

  3. steelbrain commented on Nov 16, 2026

    @steelbrain
    Owner

    Thanks for asking, this is now built in. v14 adds three options to exec and execCommand:

    // Rejects with an SSHError whose code is 'ETIMEDOUT' after 5 seconds
    await ssh.execCommand('./long-task.sh', { timeout: 5000 })
    
    // Stop it yourself with an AbortController; rejects with the abort reason
    const controller = new AbortController()
    const running = ssh.execCommand('tail -f /var/log/syslog', {
      signal: controller.signal,
      onStdout: (chunk) => process.stdout.write(chunk),
    })
    setTimeout(() => controller.abort(), 10000)

    When the timeout passes or the signal aborts, node-ssh asks the server to send killSignal (default 'TERM') to the command and closes the channel. Against OpenSSH 9.2, the command and its child processes all exited right away (sshd signals the whole process group). Two limits:

    • A command that ignores TERM keeps running; use killSignal: 'KILL' for those.
    • OpenSSH refuses to signal sessions running a forced command from authorized_keys.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions