How to allow Node.js child_process.execSync to run `scp -P 4422 root#myserver.com:/data/backups/...` without getting Permission Denied - node.js

I am running a simply Node.js process to backup my data everyday by using child_process.execSync to run:
scp -P 4422 root#myserver.com:/data/backups/dbs.zip /data/backups/dbs.zip
Notice if I run the above command directly, it will work. But when I do it in Node, the log I got is:
[2020-03-04 05:00:00] error downloading backup...Command failed:
Permission denied, please try again.
root#myserver.com: Permission denied (publickey,password).
Do I have to create a key file for Node.js' child_process to use when it fires scp? If so, how come if I run scp -i id_rsa.pem -P 4422 root#myserver.com:/data/backups/dbs.zip /data/backups/dbs.zip in Node.js it just stuck (like it even stops running any async actions such as appendFile. It also created a lot of processes called (node) and these processes cannot be killed.
const path = require('path');
const {
backupPath,
downloadPath
} = require('../../conf');
const keyPath = path.join(
__dirname,
'../../key/id_rsa.pem'
);
const downloadProcess = log => {
const { execSync } = require('child_process');
log('downloading backup...');
try {
const date = new Date();
const backupName = `db_${date.format('yyyy-MM-dd')}.tar.gz`;
const command = `scp -i ${keyPath} -P 4422 root#myserver.com:${backupPath}/${backupName} ${downloadPath}/${backupName}`;
log(`running command: ${command}`);
const stdout = execSync(command);
log(`downloaded backup ${backupName} at ${downloadPath}${'\n'}stdout:${'\n'}${stdout}`);
} catch (e) {
log(`error downloading backup...${e.message}`);
}
}
module.exports = downloadProcess;

Related

Slash command registers command from wrong folder discord.js14

I'm tired of trying to solve this. First off, here is my deployment code
const { REST, Routes } = require('discord.js');
const fs = require('node:fs');
const { client_id } = require('./config.json')
const commands = [];
// Grab all the command files from the commands directory you created earlier
const commandFiles = fs.readdirSync('./slashCommands').filter(file => file.endsWith('.js'));
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
const command = require(`./slashCommands/${file}`);
commands.push(command.data.toJSON());
}
// Construct and prepare an instance of the REST module
const rest = new REST({ version: '10' }).setToken(process.env.TOKEN);
// and deploy your commands!
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
// The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put(
Routes.applicationCommands(client_id),
{ body: commands },
);
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
// And of course, make sure you catch and log any errors!
console.error(error);
}
})();
It is supposed to get the command from the "slashCommand" folder. So I run 'node deploy-commands.js' and it works.
The problem is when I do the slash command '/ping', I get this error:
/home/runner/Nocinel/commands/ping.js:8
message.reply('🏓 **Ball is going over the net...**').then(m => { m.edit(`**🏓 Pong!\n:stopwatch: Uptime: ${Math.round(message.client.uptime / 60000)} minutes\n:sparkling_heart: Websocket Heartbeat: ${message.client.ws.ping}ms\n:round_pushpin: Rountrip Latency: ${m.createdTimestamp - message.createdTimestamp}ms**`) });
^
TypeError: m.edit is not a function
at /home/runner/Nocinel/commands/ping.js:8:73
repl process died unexpectedly: exit status 1
Now this error indicates that I am running a command from my "command" folder rather than my "slashCommand" folder. Which doesnt make sense because I explicitly coded it to only get commands from the "slash command folder"
I have restarted, deleted, waited for an hour, and tested it multiple times, it always gives the same disappointing result. I see absolutely nothing wrong with my code.
There is no problem with registring comannd (deploy-comannds.js is only registring comannds not using making them work). Problem have to be in your index.js you have to handle interaction comannds to your folder slashComannds. Registring comannds was sucessfull.
Documentation:
https://discordjs.guide/creating-your-bot/command-handling.html#loading-command-files

Creating Node.js Code to execute command on remote device using SSH connection

I`m using Node.js code and trying to connect to PaloAlto Firewall device using Node-SSH exec function, through the following code, in order to execute a command on the device and using the ssh connection and get its result into stream and then read it.
const ssh = new NodeSSH();
const {host} = config;
let connection;
connection = await ssh.connect(config);
try {
ssh.exec(command.script, { stream: 'both' }).then(function(output) {
this.logger.debug(`2DevTeam stdout: ${output.stdout}`);
this.logger.debug(`2DevTeam stderr: ${output.stderr}`);
})
} catch (ex) {
this.logger.error(`[CONNECT ${executionId}]: Execution failure:
${ex.message}"`)
}
However, it seems that the function ssh.exec is not executing and I can`t see the log nor the error of the catch;
Please Help!

Get password for node-cli and pass it on to next command in nodejs

Im trying to build a command line interface using nodejs. I have used enquirer package to prompt users for questions. I have a scenario where i need to write to /etc/hosts file. I tried running the following command using execa package
const {stdout} = await execa.command('echo "192.241.xx.xx venus.example.com venus" >> /etc/hosts', { cwd: '/etc/'})
But it does not seems to work and tried with sudo command as well
const {stdout} = await execa.command("sudo vim hosts", { cwd: '/etc/'});
How to execute it in nodejs. Basically i wanted to prompt the user for password and then need to write it to /etc/hosts file.
FYKI: im using execa for executing shell commands.
Tried the hostile.js and it didn't work either.
Here is the full code
async function executeCommand() {
try {
const {stdout} = await execa.command("echo '192.34.0.03 subdomain.domain.com' | sudo tee -a /etc/hosts", { cwd: '/etc/'});
console.log(stdout);
} catch (error) {
console.log(error);
process.exit(1);
}
}
There is a Node package for this purpose, called password-prompt:
let prompt = require('password-prompt');
let password = prompt('password: ');
And now that you have the password, you can run something like this:
let command = `echo "${password}" | sudo -S -k vim /etc/hosts`;
This solution worked for me
const { promisify } = require('util');
const exec = promisify(require('child_process').exec)
const nameOutput = await exec("echo '127.0.0.1 test.com' | sudo tee -a /etc/hosts")
This would prompt password to enter.

Pushing process to background causes high kswapd0

I have a cpu-intensive process running on a raspberry pi that's executed by running a nodejs file. Running the first command (below) and then running the file on another tab works just fine. However when I run the process via a bash shell script, the process stalls.
Looking at the processes using top I see that kswapd0 and kworker/2:1+ takes over most of the cpu. What could be causing this?
FYI, the first command begins the Ethereum discovery protocol via HTTP and IPC
geth --datadir $NODE --syncmode 'full' --port 8080 --rpc --rpcaddr 'localhost' --rpcport 30310 --rpcapi 'personal,eth,net,web3,miner,txpool,admin,debug' --networkid 777 --allow-insecure-unlock --unlock "$HOME_ADDRESS" --password ./password.txt --mine --maxpeers 100 2> results/log.txt &
sleep 10
# create storage contract and output result
node performanceContract.js
UPDATE:
performanceContract.js
const ethers = require('ethers');
const fs = require('fs')
const provider = new ethers.providers.IpcProvider('./node2/geth.ipc')
const walletJson = fs.readFileSync('./node2/keystore/keys', 'utf8')
const pwd = fs.readFileSync('./password.txt', 'utf8').trim();
const PerformanceContract = require('./contracts/PerformanceContract.json');
(async function () {
try {
const wallet = await ethers.Wallet.fromEncryptedJson(walletJson, pwd)
const connectedWallet = wallet.connect(provider)
const factory = new ethers.ContractFactory(PerformanceContract.abi, PerformanceContract.bytecode, connectedWallet)
const contract = await factory.deploy()
const deployedInstance = new ethers.Contract(contract.address, PerformanceContract.abi, connectedWallet);
let tx = await deployedInstance.loop(6000)
fs.writeFile(`./results/contract_result_xsmall_${new Date()}.txt`, JSON.stringify(tx, null, 4), () => {
console.log('file written')
})
...
Where loop is a method that loops keccak256 encryption method. It's purpose is to test diffent gas costs by alternating the loop #.
Solved by increasing the sleep time to 1min. Assume it was just a memory issue that need more time before executing the contract.

how to kill command line process start with child_process nodejs

how can i stop it, it keep running after i stop nodejs. I try process.kill() but not working
const process = require('child_process')
const child = process.exec('ping 8.8.8.8 -t')
setTimeout(()=>child.kill(2),10000)
after a few hour reading nodejs docs, i found this for who have same my problem
const process = require('child_process')
const child = process.execFile('ping 8.8.8.8',['-t'],{cwd:'your working direct'})
setTimeout(()=>child.kill(2),10000)//now kill() working
I modified your code as below to flush out the error:
const process = require('child_process')
const child = process.spawn('ping 8.8.8.8 -t') // instead of process.exec
setTimeout(() => {
console.log(child.kill(2)) // --> false == failed
}, 10000);
child.on('error', (code, signal) => {
console.log(`${code}`) // --> Error: spawn ping 8.8.8.8 -t ENOENT
});
The ping command requires an argument after the -t ( as per terminal: ping: option requires an argument -- t

Resources