#javascript #node.js #ssh #ssh2
#javascript #node.js #ssh #ssh2
Вопрос:
Пытаюсь подключиться по SSH к серверу и могу. Однако, когда я пытаюсь запустить sudo
command, мне предлагается ввести пароль указанного идентификатора пользователя. Как мне предотвратить прерывание работы клавиатуры и жестко ввести пароль, чтобы он не запрашивал пароль.
server.js
const { Client } = require('ssh2');
const conn = new Client();
conn.on('ready', () => {
console.log('Client :: ready');
conn.exec('sudo ls -lrt',{ stdin: 'passwordn', pty: true }, (err, stream) => {
if (err) throw err;
stream.on('close', (code, signal) => {
console.log('Stream :: close :: code: ' code ', signal: ' signal);
conn.end();
}).on('data', (data) => {
console.log('STDOUT: ' data);
}).stderr.on('data', (data) => {
console.log('STDERR: ' data);
});
});
}).connect({
host: 'hostname',
port: 22,
username: 'user1',
password: 'password'
});
Приглашение, которое я получаю:
STDOUT: [sudo] password for user1:
STDOUT:
sudo: timed out reading password
Комментарии:
1. Та же проблема, но не удается найти какой-либо ответ: (
2. @Aabid У меня действительно есть решение для этого. Позвольте мне добавить решение здесь.
Ответ №1:
Приведенный ниже код работает для меня.
const Client = require('ssh2').Client;
const conn = new Client();
const encode = 'utf8';
const connection = {
host: 'hostname.foo.com',
username: 'iamgroot',
password: 'root@1234'
}
conn.on('ready', function() {
// Avoid the use of console.log due to it adds a new line at the end of
// the message
process.stdout.write('Connection has been established');
let password = 'root@1234';
let command = '';
let pwSent = false;
let su = false;
let commands = [
`ls -lrt`,
`sudo su - root`,
`ls -lrt`
];
conn.shell((err, stream) => {
if (err) {
console.log(err);
}
stream.on('exit', function (code) {
process.stdout.write('Connection closed');
conn.end();
});
stream.on('data', function(data) {
process.stdout.write(data.toString(encode));
// Handles sudo su - root password prompt
if (command.indexOf('sudo su - root') !== -1 amp;amp; !pwSent) {
if (command.indexOf('sudo su - root') > -1) {
su = true;
}
if (data.indexOf(':') >= data.length - 2) {
pwSent = true;
stream.write(password 'n');
}
} else {
// Detect the right condition to send the next command
let dataLength = data.length > 2;
let commonCommand = data.indexOf('$') >= data.length - 2;
let suCommand = data.indexOf('#') >= data.length - 2;
console.log(dataLength);
console.log(commonCommand);
console.log(suCommand);
if (dataLength amp;amp; (commonCommand || suCommand )) {
if (commands.length > 0) {
command = commands.shift();
stream.write(command 'n');
} else {
// su requires two exit commands to close the session
if (su) {
su = false;
stream.write('exitn');
} else {
stream.end('exitn');
}
}
}
}
});
// First command
command = commands.shift();
stream.write(command 'n');
});
}).connect(connection);