如何远程启动和停止服务
本文关键字:服务 何远程 启动 | 更新日期: 2023-09-27 18:05:22
这是我第一次在这里发帖,第二次编码。因此,为了了解这一切是如何工作的,我尝试查找代码片段并复制/粘贴它们,直到我的应用程序似乎运行。我以前写过一些批处理和ps脚本,但说实话,我更喜欢系统管理和硬件....直到现在!
我的项目是一个简单的GUI工具,用于启动和停止某个服务器上的TeamViewer服务。我想让它尽可能地简单,它似乎很有效,直到我在同事的电脑上启动了这个应用程序,向他们展示如何使用它。
我得到错误:System。InvalidOperationException:该Dienst TeamViewer可以访问计算机MYSERVERNAME geöffnet werden。——> System.ComponentModel。Win32Exception: Zugriff verweigert,这显然与用户权限有关。所以我在谷歌上搜索了很长一段时间关于模拟和WMI服务证书,但现在我卡住了,不得不向你们寻求帮助。
这是我的代码:public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void EIN_Click(object sender, EventArgs e)
{
String svcName = "TeamViewer";
String machineName = "MYSERVERNAME";
var sc = new System.ServiceProcess.ServiceController(svcName, machineName);
sc.Start();
sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running);
}
private void AUS_Click(object sender, EventArgs e)
{
String svcName = "TeamViewer";
String machineName = "MYSERVERNAME";
var sc = new System.ServiceProcess.ServiceController(svcName, machineName);
sc.Stop();
sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped);
}
}
如果有人能帮我,我将非常高兴!注。:我的Powershell脚本工作像一个魅力,但我想让它看起来更复杂:)
Edit1:我尝试停止/启动服务的服务器不是域的成员,但域的每个成员都应该能够停止/启动服务
我发现了一个帖子,帮助我完成我的代码。可以在这里找到。
Edit1:下面是代码现在的样子:
private void EIN_Click(object sender, EventArgs e)
{
try
{
#region Code to start the service
string serviceName = "TeamViewer";
string IP="actual-IP-address";
string username ="actual-username";
string password ="actual-password";
ConnectionOptions connectoptions = new ConnectionOptions();
//connectoptions.Impersonation = ImpersonationLevel.Impersonate;
connectoptions.Username = username;
connectoptions.Password = password;
//IP Address of the remote machine
ManagementScope scope = new ManagementScope(@"''" + IP + @"'root'cimv2");
scope.Options = connectoptions;
//WMI query to be executed on the remote machine
SelectQuery query = new SelectQuery("select * from Win32_Service where name = '" + serviceName + "'");
using (ManagementObjectSearcher searcher = new
ManagementObjectSearcher(scope, query))
{
ManagementObjectCollection collection = searcher.Get();
foreach (ManagementObject service in collection)
{
if (service["Started"].Equals(false))
{
//Start the service
service.InvokeMethod("StartService", null);
//here i added a picture box which shows a green button when the service is started
pictureBox1.Image = Properties.Resources._120px_Green_Light_I_svg;
}
}
}
#endregion
}
catch (NullReferenceException)
{
}
}