英文:
Is it possible to execute command line/powershell commands from a svelte backend?
问题
我想获取网络上一台计算机的Windows服务列表。通常,我会使用PowerShell命令来实现这一点,但我可以从SvelteKit应用程序的后端进行操作吗?也许可以使用服务器或API文件来实现?如果可以,如何操作?
英文:
I'm looking to get a list of windows services on a machine on my network. Running a powershell command would be how I achieve this normally, but can I do this from a backend of a sveltekit app? Perhaps a server or api file? If so, how?
答案1
得分: 1
你可以执行任何有效的代码,对于默认的后端(通常是NodeJS),只是关于如何在Node中执行的问题。
模块 child_process
具有用于启动新进程的各种函数,例如:
// +page.server.js
const { exec } = await import('child_process')
export const load = async () => {
const computerName = 'localhost'
const stdout = await new Promise((resolve, reject) => {
exec(
`powershell -command "Get-Service -ComputerName ${computerName}` +
'| Where-Object -Property Status -EQ -Value Running' +
'| Select-Object -Property Name"',
(err, stdout) => err ? reject(err) : resolve(stdout)
);
});
const items = stdout.split('\n')
.map(x => x.trim())
.filter(x => x)
.slice(2); // removes table header
return { items };
}
请参阅 数据加载文档。
英文:
You can execute any valid code for the given backend, which by default should be NodeJS. So it is just a question of how to do that in Node.
The module child_process
has various functions for starting new processes, e.g.
// +page.server.js
const { exec } = await import('child_process')
export const load = async () =>
{
const computerName = 'localhost'
const stdout = await new Promise((resolve, reject) =>
{
exec(
`powershell -command "Get-Service -ComputerName ${computerName}` +
'| Where-Object -Property Status -EQ -Value Running' +
'| Select-Object -Property Name"',
(err, stdout) => err ? reject(err) : resolve(stdout)
);
});
const items = stdout.split('\n')
.map(x => x.trim())
.filter(x => x)
.slice(2); // removes table header
return { items };
}
See also data loading docs.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论