Reputation: 195
Using node ssh2 module, this is what I need to do
1. ssh to a server as a local user
2. sudo as oracle : sudo su oracle
3. run commands
I am unable to sudo su oracle and hence cant run any commands. The local user has the privilege to become oracle and so no password need to be provided.
I can run multiple commands as one like - cd /home;./run.sh
But If i need to run commands where the first command is sudo su oracle;cd /home; ./run.sh
I don't get a response
//code snippet
let fs = require('fs'),
Client = require('ssh2').Client;
const executeRemote = (command, remoteServer, user, privateKey) => {
return new Promise((resolve, reject) => {
let conn = new Client();
let outputData = '';
console.log('privatekey is ' + privateKey);
conn.on('ready', function () {
conn.exec((command), function (err, stream) {
if (err) {
reject(err);
}
// eslint-disable-next-line no-unused-vars
stream.on('close', function (code, signal) {
console.log('outputData is ', outputData);
console.log('code is ' + code);
if (code === 0)
resolve(outputData);
else
reject(outputData);
conn.end();
}).on('data', function (data) {
//console.log('data is ', data.toString());
outputData = outputData + data.toString();
}).stderr.on('data', function (data) {
console.log('stderr data Error- ' + data.toString());
//check if data.toString() has WARNING
let regex = '[WARNING]';
if (data.toString().match(regex))
outputData = outputData + data.toString();
else
reject(new Error('Failed to run the command- ' + command + ' .Error- ' + data.toString()));
});
});
}).connect({
host: remoteServer,
port: 22,
username: user,
privateKey: require('fs').readFileSync(privateKey)
});
});
};
Once I can ssh as local user, I want to run the command to sudo as oracle and then run other commands. Is there a code snippet some one can share how they sudo su as any user and then run commands
Upvotes: 3
Views: 2003
Reputation: 848
You can write the password on prompt:
ssh.exec('sudo su - ' + sudoUserName, { pty: true }, function (err, stream) {
stream.on('close', (code, signal) => {
//clean up
}).on('data', (data) => {
if (data.toString().substring(0, sudoUserName.length) === sudoUserName) {
//logged in successfully
}
else {
//enter password
stream.write(password + '\n');
}
}).stderr.on('data', (data) => {
stream.close();
});
}
Upvotes: 1