【问题标题】:Linux with SSH.NET : “sorry, you must have a tty to run sudo”带有 SSH.NET 的 Linux:“抱歉,您必须有一个 tty 才能运行 sudo”
【发布时间】:2018-02-10 06:27:21
【问题描述】:

我正在使用 Renci.SshNet 并且远程 Linux 服务器以某种方式知道我没有使用终端仿真器进行连接。所以:

using Renci.SshNet;

var connectionInfo = new ConnectionInfo("host","username", new PasswordAuthenticationMethod("username", "password"));
using (var client = new SshClient(connectionInfo))
client.Connect();

var test = client.RunCommand("sudo mycommand");

结果

"sudo: sorry, you must have a tty to run sudo"

问题:如何使用 SSH.NET 模拟终端模拟器?

我在https://refactoragain.com/2016/05/27/ssh-net-echo-sudo-s/ 上找到的以下代码似乎创建了一个终端仿真:

SshClient client = new SshClient(server_address, 22, login, password);
client.Connect();

IDictionary<Renci.SshNet.Common.TerminalModes, uint> modes = 
new Dictionary<Renci.SshNet.Common.TerminalModes, uint>();
termkvp.Add(Renci.SshNet.Common.TerminalModes.ECHO, 53);

ShellStream shellStream = 
sshClient.CreateShellStream("xterm", 80, 24, 800, 600, 1024, modes);
var output = shellStream.Expect(new Regex(@"[$>]")); 

shellStream.WriteLine("sudo sh/home/my_user_name/scripts/install_and_configure.sh"); 
output = shellStream.Expect(new Regex(@"([$#>:])"));
shellStream.WriteLine(password);
client.Disconnect();

但这对我来说是希腊语,因为它需要一个主目录,而我的用户名似乎没有。为什么我必须断开连接? (代码最后一行)

我只想运行 Linux 命令并在我的代码中获取返回字符串!

祝大家周末愉快。

【问题讨论】:

  • 你是如何创建client的?

标签: c# linux ssh ssh.net


【解决方案1】:

大概my command 里面有sudo

sudo 是交互式的,要求输入密码,而RunCommand 不提供任何向命令发送输入的功能。

您需要改用ShellStream

var sh = client.CreateShellStream("", 0, 0, 0, 0);
sh.WriteLine("my command");
sh.WriteLine("sudo password");

【讨论】:

  • 是的。当您在 Linux 上 telnet/ssh/打开命令提示符时,在提示符处输入 my command(我假设包含 sudo)会发生什么?
  • 当我输入 sudo mycommand 时,一切正常。只是我不能在C#中重复它
  • 当你输入sudo mycommand时,是否提示输入密码?
  • 没有。您的代码似乎有效!但只有当我逐步使用 F10 时。显然,每次操作之间都需要时间(我正在创建 ftp 客户端,并且该命令在单独的命令中要求用户名、密码和配额)有没有办法等待 Linux 服务器的回答?
  • 所以:sh.WriteLine("sudo imp_createftp ftptestole5"); sh.WriteLine("ftptestole5"); sh.WriteLine("ftptestole5"); sh.WriteLine("1234");当我慢慢地走过去时,它就起作用了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 2015-10-07
  • 1970-01-01
  • 2015-06-29
相关资源
最近更新 更多