繁体   English   中英

通过计划任务运行 C# 脚本

[英]Run C# script through scheduled task

我在 c# 中开发了一个小脚本,用于查询 SQL Server 并根据某些条件将计算机对象添加到某些 Active Directory 组。 当我使用具有从 Active Directory 组添加/删除对象的必要权限的帐户运行脚本时,该脚本工作正常。

当我尝试安排作业时,它使用“SYSTEM”帐户从服务器自动运行它不起作用,我收到“拒绝访问”我已经更新了绑定帐户以使用有效帐户中的凭据,但我仍然有同样的问题。

> Error Message:
> *2020-01-13 18:32:30,984 [1] ERROR TestAD.clsActiveDirectory - Error occured when trying to add computerobject abcdefg-a10 to group. Error
> message: Access is denied.*

使其工作的唯一方法是使用实​​际帐户作为帐户来运行计划任务,但是,问题是我们公司的政策不允许我们存储密码,因此我需要登录该帐户才能运行此脚本.

代码片段

                    de.Username = "testing@test.com";
                    de.Password = "xxxxxxxxx";
                    de.AuthenticationType = AuthenticationTypes.Secure;
                    de.AuthenticationType = AuthenticationTypes.Sealing;
                    de.AuthenticationType = AuthenticationTypes.Delegation;
                    de.Properties.Count.ToString();
                    ds.SearchRoot = de;
                    ds.Filter = "(&(objectClass=computer)(name=" + _myComputerName.ToString() + `"))";`
                    ds.PropertiesToLoad.Add("memberof");
                    ds.PropertiesToLoad.Add("distinguishedname");
                    ds.SizeLimit = 10;
                    ds.PageSize = 0;
                    ds.SearchScope = System.DirectoryServices.SearchScope.Subtree;

我尝试添加一些“AuthenticationTypes”以查看是否有所不同但仍然相同

任何帮助,将不胜感激

谢谢。

您是否尝试过使用 SQL Server 代理? 我的公司使用它们而不是计划任务。 它们可能不太优雅,但它可能是您的情况的一个很好的替代方案。

  • 创建一个 SQL Server 代理,该代理调用带有或不带有参数的可执行文件。
    • 如果您无法从托管操作系统调用可执行文件,则可以调用网络上的 SSIS 包来为您调用可执行文件。

如果您需要更多详细信息,请告诉我。

我发现了这个问题,最后很直接。 Active Directory 流程如下 - 使用我的特殊帐户绑定到 Active Directory 并搜索计算机对象并验证是否需要将其添加到 Active Directory 组 - 如果需要添加,请执行第二次绑定到 Active Directory 组并添加计算机对象。 ==> 使用计划任务或在“SYSTEM”上下文下运行时,此部分失败

失败原因:当我第二次绑定时,我没有指定任何凭据,因此如果我运行脚本,我的帐户有足够的权限将计算机对象添加到组,它将使用默认凭据 (SYSTEM)。

我更新了第二个绑定的代码以包含绑定凭据,现在它按预期工作。

我希望这对必须解决类似问题的其他人有所帮助。

旧代码

    try
    {
        DirectoryEntry ent = new DirectoryEntry(bindString);
        ent.Properties["member"].Add(newMember);
        ent.CommitChanges();
    }

新代码

    try
    {
        DirectoryEntry ent = new DirectoryEntry(bindString);
        ent.AuthenticationType = AuthenticationTypes.Secure;
        ent.AuthenticationType = AuthenticationTypes.Sealing;
        ent.AuthenticationType = AuthenticationTypes.Delegation;
        ent.Username = "test123@test.com";
        ent.Password = "test123";
        ent.Properties["member"].Add(newMember);
        ent.CommitChanges();
    } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM