【问题标题】:Need to understand how to run a simple shell script in a azure vm lunix需要了解如何在 azure vm linux 中运行简单的 shell 脚本
【发布时间】:2021-08-25 15:16:52
【问题描述】:

我正在关注此文档并尝试使用此文档在 VM 中运行 shell 脚本:

https://docs.microsoft.com/en-us/rest/api/compute/virtual-machines-run-commands/run-command

我的第一个问题是:当我使用一个简单的脚本时,例如在 post 方法的输入中输入 'ls',我得到状态 202 并且没有结果消息,谁能告诉我为什么?

我的第二个问题是:我想运行一个脚本文件myscript.sh 并传递一些参数给它。但我不知道如何在输入中将参数传递给脚本

谁能帮我理解或告诉我怎么做,我正在使用 .NET 和 C#。

这是我现在的代码

using (var client = new HttpClient())
{
    Body body = new Body
                    {
                         commandId = "RunShellScript",
                         script = new List<string> { "ls"}
                    };

    // Generate Bearer Token
    var azureServiceTokenProvider = new AzureServiceTokenProvider();
    string managementApiUrl = "https://management.azure.com/";
    var accessToken = azureServiceTokenProvider.GetAccessTokenAsync(managementApiUrl, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx").Result;
            
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

    // Call Post Method
    HttpResponseMessage response = await client.PostAsJsonAsync("https://management.azure.com/subscriptions/xxxx/resourceGroups/xxx/providers/Microsoft.Compute/virtualMachines/simpleLinuxVM/runCommand?api-version=2021-03-01", body);

    // Fetch Result
    if (response.IsSuccessStatusCode)
    {
        string finalResponse = await response.Content.ReadAsStringAsync();

        Console.WriteLine(string.Format("Result:", finalResponse.ToString()));
    }
    else
    {
        Console.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode));
  
        string responseContent = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseContent);
    }
}

【问题讨论】:

    标签: c# api shell azure-functions azure-virtual-machine


    【解决方案1】:

    根据你这里写的代码

    script = new List<string> {"ls"}
    

    “ls”将被视为“脚本”对象列表中的字符串。这就是为什么您没有得到任何结果的原因,尽管有 s Success 状态。

    我发现了与您的问题相关的类似thread。为此,您可以制作 myscript。 sh 使用下面的代码运行。

    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.CreateNoWindow = false;
    startInfo.UseShellExecute = false;
    startInfo.FileName = "YourFile.exe";
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    startInfo.Arguments = "";//Arguments should be here
    using (Process exeProcess = Process.Start(startInfo))
    {
        exeProcess.WaitForExit();
    }
    
    

    并使用 exeProcess.StandardOutput.ReadToEnd(); 获取结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      • 1970-01-01
      • 2018-05-13
      • 2019-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多