【问题标题】:bat file and windows services with network path, problems with credentials具有网络路径的 bat 文件和 Windows 服务,凭据问题
【发布时间】:2023-04-03 06:21:01
【问题描述】:

你好吗?我的凭据有问题,我不知道如何在 bat 文件中传递密码和用户。请阅读上下文。

我创建了一个 Windows 服务,它使用 args 参数从 bat 文件中获取一些配置值。该服务在所需位置写入一个 txt 文件,但是 这是我的 Windows 服务的一些基本代码:

static void Main(string[] args)
    {  //args comes from the bat file

        CmdLineArgs cmdArgs = new CmdLineArgs(args);

        //pass the values for mydirectory from args

        AppConfig.NetworkDirectory = cmdArgs.GetArg("/mydirectory");

        writefile(AppConfig.NetworkDirectory,"text for file");

         if(couldntwriteinpath())
            { //...manage  error
                                     }
     }

writefile 过程:

//this is a very simple way of doing this, so you can have an idea of what is going on
public static void writefile(string path, string text)
{ string savepathname=path+"\myfile.txt";
//uses the class File.writealltext function
  File.WriteAllText(savepathname, text);
 }

bat 文件:

cd C:\Windows\System32

sc.exe stop MyService

sc.exe delete MyService

timeout 3

sc.exe create MyService binPath="\"C:\apps\MyService\MyService.exe\" /mydirectory"\\192.168.90.x\homes\writefolder\"" start= auto
 sc.exe start MyService
PAUSE

**问题是我收到一个错误:“用户名或密码不正确”。

你能帮帮我吗?我尝试做所有的 stackoverflow 答案,如 https://stackoverflow.com/questions/3854026/how-to-give-credentials-in-a-batch-script-that-copies-files-to-a-network-locatio,https://stackoverflow.com/questions/303045/connecting-to-a-network-folder-with-username-password-in-powershell 等。但没有奏效。

我想在 bat 中插入用户名和密码。因此,在调用 File.WriteAllText 过程时,它也会获取凭据。

谢谢

【问题讨论】:

  • 信息很少。发布您的 bat 代码,以便我们了解发生了什么。

标签: batch-file cmd path windows-services


【解决方案1】:

如果我理解,File.WriteAllText 过程由服务运行,但它没有写入目标文件的凭据。因此,您希望使用执行此类任务所需的凭据启动服务。

您可以使用sc 命令的obj=password= 开关为服务设置凭据,如

@echo off

pushd %__APPDIR__% & rem cd C:\Windows\System32

setlocal
set "user=system\username"
set "pass=p@ssword"

sc.exe stop MyService

sc.exe delete MyService

timeout 3

sc.exe create MyService binPath="\"C:\apps\MyService\MyService.exe\" /mydirectory"\\192.168.90.x\homes\writefolder\"" start= auto obj= "%user%" password= "%pass%"
sc.exe start MyService

endlocal
popd
PAUSE

exit/B

注意:不确定它是否适合您,通常sc switches 期望 = 符号后面有一个空格,而您的 binPath= 没有。

【讨论】:

  • 感谢您的回答!!我要试一试,让你知道。
  • 嘿,我遇到了一个小问题,“帐户名无效或不存在,或者指定的帐户名的密码无效”。我已经尝试使用 user=system\mycomputerusername 和 user=mycomputerusername。谢谢
  • @theman,不确定我是否理解你。当你说mycomputerusername 只是usernamemachinename_username。例如,我的计算机名是lenovo,我的用户名是miguel,所以在我的情况下obj= "lenovo\miguel" password= "p@ssword" 可以完美运行。请给我反馈,因为如果它不起作用,可能是该帐户没有提升权限。还有另外两种方法可以做到这一点,使用 powershell 或更新注册表项。我们可能会使用其中之一来执行所需的任务
  • 非常感谢您的帮助!它确实有效,我必须使用以下设置进行更改: user=mycomputername\username 。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多