【问题标题】:C# connect and run commands to Dell SwitchC# 连接并运行命令到 Dell Switch
【发布时间】:2018-03-06 08:35:43
【问题描述】:

我想连接到戴尔 X1008 交换机并运行一些命令。我使用过 C# Tamir.SharpSsh 和 Renci.SshNet 库。

using Tamir.SharpSsh;

SshExec exec = new SshExec("ip address", "username", "password");
exec.Connect();
var output = exec.RunCommand("show vlan");
exec.Close();

但我的代码冻结在“exec.RunCommand("show vlan")”行。

using Renci.SshNet;
using (var client = new SshClient(Host, UserName, Password))
{
    try
    {
        client.Connect();
    }
    catch (Exception ex)
    {

        throw;
    }

    var command = client.CreateCommand("show vlan");
    return command.Execute();
}

这里我的代码冻结在“var command = client.CreateCommand(cmd)”行。

有人知道吗?

仅供参考:以上代码适用于 Cisco 交换机。我可以通过 Putty 软件连接到 Dell 和 Cisco 交换机,并且可以从 putty 运行命令。我的要求是从 C# 应用程序运行命令。

问候

拉维

【问题讨论】:

  • 1) 甚至不要尝试 SharpSSh,那是一个死项目。 2) 你确定它挂在CreateCommand 上吗?这几乎没有任何作用。我希望它能够挂在command.Execute 上。 3) 可以使用plink hostname show vlan 执行命令吗? (PuTTY 包中的 PLink)

标签: c# .net networking ssh putty


【解决方案1】:

Renci.SshNet 是更好的选择。

查看该方法的响应,命令有超时。

public string ExecuteCommandSsh(string host, int port, string username, string password, string[] commands)
{
    var returnMessage = string.Empty;

    try
    {
        using (var client = new SshClient(host, port, username, password))
        {
            //Create the command string
            var fullCommand = string.Empty;
            foreach (var command in commands)
            {
                fullCommand += command + "\n";
            }

            client.Connect();
            var sshCommand = client.CreateCommand(fullCommand);
            sshCommand.CommandTimeout = new TimeSpan(0, 0, 10);

            try
            {
                sshCommand.Execute();
                returnMessage = sshCommand.Result;
            }
            catch (SshOperationTimeoutException)
            {
                returnMessage = sshCommand.Result;
            }


            client.Disconnect();
        }
    }
    catch (Exception e)
    {
        //other exception
    }

    return returnMessage;
}

【讨论】:

  • 这如何回答这个问题?您已经发布了 OP 正在使用的相同代码。 + 另外,“Renci.SshNet 是更好的库 SSH.NET” 是什么意思?
  • OP 有两个库 Tamir.SharpSsh 和 Renci。我的示例有命令超时。超时是否可以显示响应。
猜你喜欢
  • 2011-06-21
  • 1970-01-01
  • 1970-01-01
  • 2021-07-20
  • 2021-11-14
  • 2010-11-06
  • 2011-10-31
  • 1970-01-01
相关资源
最近更新 更多