zza*_*ndy 10 .net c# remote-access environment-variables
我需要一种方法来扩展远程机器上的环境变量.
假设我有一个文件夹的路径,%appdata%\MyApp\Plugins或者%ProgramFiles%\MyCompany\MyApp\Plugins我想列出该文件夹中的文件以进行审计.唯一的问题是我想在远程计算机上执行此操作,但我有管理员访问权限.
一个额外的问题(但不是必不可少的)是如何为远程机器上的给定用户执行此操作?
您将使用GetFolderPath.您可以使用许多不同的SpecialFolder值,包括ProgramFiles和ApplicationData
string path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
Run Code Online (Sandbox Code Playgroud)
然后你可以把它与你的其他路径结合起来
string full_path = Path.Combine(path, "\MyApp\Plugins");
Run Code Online (Sandbox Code Playgroud)
在远程计算机上,它看起来像你可以尝试像这样
ConnectionOptions co = new ConnectionOptions();
// user with sufficient privileges to connect to the cimv2 namespace
co.Username = "administrator";
// his password
co.Password = "adminPwd";
ManagementScope scope = new ManagementScope(@"\\BOBSMachine\root\cimv2", co);
SelectQuery query = new SelectQuery("Select windowsdirectory from Win32_OperatingSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
foreach (ManagementObject windir in searcher.Get())
Console.WriteLine("Value = {0}", windir["windowsdirectory"]);
Run Code Online (Sandbox Code Playgroud)
或者从这里获取所有远程环境变量及其值的列表
public static void GetSysInfo(string domain, string machine, string username, string password)
{
ManagementObjectSearcher query = null;
ManagementObjectCollection queryCollection = null;
ConnectionOptions opt = new ConnectionOptions();
opt.Impersonation = ImpersonationLevel.Impersonate;
opt.EnablePrivileges = true;
opt.Username = username;
opt.Password = password;
try
{
ManagementPath p = new ManagementPath("\\\\" +machine+ "\\root\\cimv2");
ManagementScope msc = new ManagementScope(p, opt);
SelectQuery q= new SelectQuery("Win32_Environment");
query = new ManagementObjectSearcher(msc, q, null);
queryCollection = query.Get();
Console.WriteLine(queryCollection.Count);
foreach (ManagementBaseObject envVar in queryCollection)
{
Console.WriteLine("System environment variable {0} = {1}",
envVar["Name"], envVar["VariableValue"]);
}
}
catch(ManagementException e)
{
Console.WriteLine(e.Message);
Environment.Exit(1);
}
catch(System.UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
Environment.Exit(1);
}
}
Run Code Online (Sandbox Code Playgroud)
OP编辑:
也%AppData%可以从注册表(可以远程进行)中找到HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders和程序文件的HKLM\Software\Microsoft\Windows\CurrentVersion下ProgramfilesDir.