可以从Svelte后端执行命令行/PowerShell命令吗?

huangapple go评论58阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年7月13日 14:04:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76676354.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定