Skip to main content

Log in to comment and vote

Comments1

  • IntinteDAO

    •

    Jan 7

    I write using AI my own SSH Support

    • Add code piece

    • Add 4 inputs

      • host → IP (127.0.0.1 might not work in self host if on docker)

      • username → username (eg. fervi)

      • password → password (eg. password)

      • command → command (eg. whoami)

    • Add package: ssh2

    Source code
    ```
    import { createRequire } from 'module';

    const require = createRequire(import.meta.url);

    export const code = async (inputs) => {

    const { Client } = require('ssh2');

    const conn = new Client();

    // 1. Input Validation

    if (!inputs.host) throw new Error("ERROR: Missing 'host' field in Inputs.");

    if (!inputs.username) throw new Error("ERROR: Missing 'username' field in Inputs.");

    // Critical check: Does the command exist?

    if (!inputs.command) {

    throw new Error("ERROR: Missing 'command' field in Inputs! You must provide a command to execute (e.g., 'ls -la').");

    }

    const config = {

    host: inputs.host.trim(),

    port: inputs.port ? parseInt(inputs.port) : 22,

    username: inputs.username.trim(),

    readyTimeout: 20000,

    // Enable tryKeyboard in case the server requires it instead of standard password auth

    tryKeyboard: true

    };

    // 2. Authentication Logic

    if (inputs.privateKey) {

    config.privateKey = inputs.privateKey;

    } else if (inputs.password) {

    config.password = inputs.password;

    } else {

    throw new Error("You must provide either 'password' or 'privateKey' in Inputs.");

    }

    // Handle keyboard-interactive event (required for some servers)

    conn.on('keyboard-interactive', (name, instructions, instructionsLang, prompts, finish) => {

    // If the server asks for a password in interactive mode, provide it here

    if (prompts.length > 0 && prompts[0].prompt.toLowerCase().includes('password')) {

    finish([inputs.password]);

    } else {

    finish([]);

    }

    });

    return new Promise((resolve, reject) => {

    conn.on('ready', () => {

    // Connection established, executing command

    conn.exec(inputs.command, (err, stream) => {

    if (err) {

    conn.end();

    return reject(new Error(`Command execution error: ${err.message}`));

    }

    let stdoutData = "";

    let stderrData = "";

    stream.on('close', (code, signal) => {

    conn.end();

    resolve({

    success: code === 0,

    code: code,

    stdout: stdoutData.trim(),

    stderr: stderrData.trim()

    });

    }).on('data', (data) => {

    stdoutData += data.toString();

    }).stderr.on('data', (data) => {

    stderrData += data.toString();

    });

    });

    }).on('error', (err) => {

    conn.end();

    reject(new Error(`SSH Connection Error: ${err.message}`));

    }).connect(config);

    });

    };
    ```