首页 > 解决方案 > 通过 SSH.NET 将用户切换到 root

问题描述

我正在使用 SSH.NET 来获取外部磁带驱动器的一些信息。连接和执行一些基本命令对我来说非常好:

ConnectionInfo connNfo = new ConnectionInfo("10.12.2.97", 22, "loginuser",
new AuthenticationMethod[]
{
// Password based Authentication
new PasswordAuthenticationMethod("loginuser","password")
}
);

using (var client = new SshClient(connNfo))
{
    client.Connect();

    //This command works fine
    using (var cmd = client.CreateCommand("ls"))
    {
        string result = cmd.Execute();
    }
}

但是现在我必须切换到 root 用户才能执行我需要的扩展命令。由于安全限制,最初无法使用 root 用户登录。参考这篇文章How to run commands by sudo and enter password by ssh .net c#我试过这个代码块:

using (var cmd = ssh.RunCommand("echo 'rootpassword' | sudo -u root -S fsstate"))
{
if (cmd.ExitStatus == 0)
    Console.WriteLine(cmd.Result);
else
    Console.WriteLine(cmd.Error);
}

但后来我总是收到这个错误信息:

sudo:未知用户:root
sudo:无法初始化策略插件

更新 1: 工作 PuTTY 命令

我在这里做错了什么?

标签: c#sshssh.net

解决方案


推荐阅读