Javascript 无法使用Node.js ssh2模块将用户切换到root用户
正在尝试使用SSH连接到服务器,并且能够。但是,当我尝试运行Javascript 无法使用Node.js ssh2模块将用户切换到root用户,javascript,node.js,ssh,ssh2,Javascript,Node.js,Ssh,Ssh2,正在尝试使用SSH连接到服务器,并且能够。但是,当我尝试运行sudo命令时,它会提示我输入所提到的用户ID的密码。如何防止任何键盘中断和硬编码密码,使其不会提示输入密码 server.js const { Client } = require('ssh2'); const conn = new Client(); conn.on('ready', () => { console.log('Client :: ready'); conn.exec('
sudo
命令时,它会提示我输入所提到的用户ID的密码。如何防止任何键盘中断和硬编码密码,使其不会提示输入密码
server.js
const { Client } = require('ssh2');
const conn = new Client();
conn.on('ready', () => {
console.log('Client :: ready');
conn.exec('sudo ls -lrt',{ stdin: 'password\n', 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
下面的代码适用于我
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 && !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 && (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('exit\n');
} else {
stream.end('exit\n');
}
}
}
}
});
// First command
command = commands.shift();
stream.write(command + '\n');
});
}).connect(connection);
同样的问题,但无法给出任何答案:(@Aabid)我确实有解决方案。让我在这里添加解决方案。