Execute function "executeRemoteScript" when user clicks a button (api ?)
Unanswered
American black bear posted this in #help-forum
American black bearOP
Following a question I made yesterday, I have this code that executes a command after connecting to a remote host (I'm on the same network and disconnected from the internet so security issues is not a thing in this case)
and this works fine when I go to the page but the command is executed when the page loads.
What I need is a page with a Button and only when the user clicks the button, the "executeRemoteScript" is executed. I tried to do that but I it seems that I should use the api folder.
Can someone help me on how to do this? I was expecting that would be more direct.
const { NodeSSH } = require('node-ssh');
const ssh = new NodeSSH();
export default async function executeRemoteScript() {
try {
// Connect to the remote server
await ssh.connect({
host: 'myHost',
username: 'myUser',
password: 'myPassword')
});
console.log('Successfully connected to the remote server.');
// Execute the remote script
const { stdout, stderr } = await ssh.execCommand("ls -la");
if (stderr) {
console.error('Script Error:', stderr);
} else {
console.log('Script Output:', stdout);
}
} catch (error) {
console.error('Error:', error);
} finally {
// Disconnect from the remote server
ssh.dispose();
}
}and this works fine when I go to the page but the command is executed when the page loads.
What I need is a page with a Button and only when the user clicks the button, the "executeRemoteScript" is executed. I tried to do that but I it seems that I should use the api folder.
Can someone help me on how to do this? I was expecting that would be more direct.
5 Replies
Asian black bear
Where are you currently calling this function?
American black bearOP
this code is in "app/test/page.tsx". If I go to http://<NEXT_IP>:<NEXT_PORT/test, the command "ls -la" is executed, ie, the executeRemoveScript is run on page load.
I tried to use the code below without success.
"app/test/page.tsx":
and "app/test/sshUtility.js":
I tried to use the code below without success.
"app/test/page.tsx":
"use client"
import { useState } from 'react';
import { createRemoteFolder } from './sshUtility';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
const CreateFolder = () => {
const [folderName, setFolderName] = useState('');
const [message, setMessage] = useState('');
const handleCreateFolder = async () => {
host = 'myHost';
username = 'myUser';
password = 'myPassword');
const result = await createRemoteFolder(host, username, password, folderName);
setMessage(result.message);
};
return (
<div className="flex w-full max-w-sm items-center space-x-2">
<Input type="text" placeholder="Enter folder name" value={folderName}
onChange={(e) => setFolderName(e.target.value)}
/>
<Button onClick={handleCreateFolder}>Create Folder</Button>
<p>{message}</p>
</div>
);
};
export default CreateFolder;and "app/test/sshUtility.js":
const { NodeSSH } = require('node-ssh');
const ssh = new NodeSSH();
async function createRemoteFolder(host, username, password, folderName) {
try {
await ssh.connect({
host,
username,
password,
});
const folderPath = `/home/${folderName}`;
const { stdout, stderr } = await ssh.execCommand(`mkdir -p ${folderPath}`);
if (stderr) {
return { success: false, message: `Failed to create folder ${folderPath}. Error: ${stderr}` };
} else {
return { success: true, message: `Successfully created folder ${folderPath}. Output: ${stdout}` };
}
} catch (error) {
return { success: false, message: `Error: ${error.message}` };
} finally {
ssh.dispose();
}
}
module.exports = { createRemoteFolder };Asian black bear
This is a strange one as from what I can see you are not calling the functions apart from on the button, therefore I am unsure why the function is being executed at all as you are not telling it to run apart from the button is pressed?
American black bearOP
it works with the first code. with the second one (code in two parts) it doesn't. Sorry if I didnt' explain myself correctly
Asian black bear
Have you console logged to make sure that the values are being passed in correctly to create the folder? This is going to give more information about where the function is failing. I understand the question now, thank you for clarifying