microsoft / node-pty

Fork pseudoterminals in Node.JS
Other
1.42k stars 233 forks source link

Timeout while executing commands #591

Closed as2r9 closed 1 year ago

as2r9 commented 1 year ago

Environment details

Issue description

I wrote a code to execute a set of commands that are given in the form of array.


const { spawn } = require('node-pty');

// Start a new PTY process
const shell = spawn('bash');

const commands = [
  'ssh server_address',
  './ultimateSSH.sh',
  'ls',
  'ssh server_addressl',
  'sudo su - docker',
  'docker ps',
  'docker exec -it  docker_number` bash',
  'ls'
];

and i wrote the code in such a way that if there is any user input prompt present like a password prompt. that would be given through code

the following is the code


let commandIndex = 0;
let state = 'command';
// Listen for data from the PTY process
shell.on('data', (data) => {
  console.log(data);

  // Check the current state
  if (state === 'command') {
    // Send the next command
    shell.write(`${commands[commandIndex]}\n`);
    console.log(commandIndex+' this is number');
    // Change the state to wait for input
    state = 'input';
  } else if (state === 'input') {
    // Check if the current command requires input
    if (data.includes('password') || data.includes('Please input the environment you want to access:')) {
      // Provide input
      if (commandIndex === 0 || commandIndex === 2 || commandIndex === 3 || commandIndex === 4) {
        shell.write(password+'\n');
        console.log(commandIndex+' this is number');
        //console.log(commandIndex+'this is the command number');
      } else if (commandIndex === 1) {
        console.log(commandIndex+' this is number');
        shell.write('2\n');
        shell.write('1\n');
      }
      else if( commandIndex === 6 || commandIndex === 5){
        console.log(commandIndex+' this is number');
        shell.write('\n');
      }

      // Move on to the next command
      commandIndex++;

      // Check if there are more commands to execute
      if (commandIndex < commands.length) {
        // Change the state back to command
        state = 'command';
      } else {
        // We're done, so exit the PTY process

        shell.write('exit\n');
      }
    }
  }
});

now as you can see from the commands array there are 8 commands but the execution gets stuck at the 6th command. i.e. The "docker ps" runs perfectly but I am unable to execute the "docker exec - it bash" command. There isn't any timeout or the code isn't executing the exit command. It just waits for a new command.