本文整理汇总了C#中Renci.SshNet.SshClient.CreateCommand方法的典型用法代码示例。如果您正苦于以下问题:C# SshClient.CreateCommand方法的具体用法?C# SshClient.CreateCommand怎么用?C# SshClient.CreateCommand使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Renci.SshNet.SshClient
的用法示例。
在下文中一共展示了SshClient.CreateCommand方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
// Setup Credentials and Server Information
ConnectionInfo ConnNfo = new ConnectionInfo("dan.hangone.co.za", 224, "Dan",
new AuthenticationMethod[]{
// Pasword based Authentication
new PasswordAuthenticationMethod("Dan","letmein5")/*,
// Key Based Authentication (using keys in OpenSSH Format)
new PrivateKeyAuthenticationMethod("username",new PrivateKeyFile[]{
new PrivateKeyFile(@"..\openssh.key","passphrase")
}),*/
}
);
/*
// Execute a (SHELL) Command - prepare upload directory
using (var sshclient = new SshClient(ConnNfo))
{
sshclient.Connect();
using (var cmd = sshclient.CreateCommand("mkdir -p /tmp/uploadtest && chmod +rw /tmp/uploadtest"))
{
cmd.Execute();
Console.WriteLine("Command>" + cmd.CommandText);
Console.WriteLine("Return Value = {0}", cmd.ExitStatus);
}
sshclient.Disconnect();
}
*/
/*
// Upload A File
using (var sftp = new SftpClient(ConnNfo))
{
string uploadfn = "Renci.SshNet.dll";
sftp.Connect();
sftp.ChangeDirectory("/tmp/uploadtest");
using (var uplfileStream = System.IO.File.OpenRead(uploadfn))
{
sftp.UploadFile(uplfileStream, uploadfn, true);
}
sftp.Disconnect();
}
*/
// Execute (SHELL) Commands
using (var sshclient = new SshClient(ConnNfo))
{
sshclient.Connect();
// quick way to use ist, but not best practice - SshCommand is not Disposed, ExitStatus not checked...
Console.WriteLine(sshclient.CreateCommand("/log print").Execute());
Console.WriteLine(sshclient.CreateCommand("/int print").Execute());
Console.WriteLine(sshclient.CreateCommand("/ppp secret print").Execute());
sshclient.Disconnect();
}
Console.ReadKey();
}
示例2: ExecuteCommand
private static String ExecuteCommand(SshClient sshClient, String command)
{
if (!sshClient.IsConnected)
sshClient.Connect();
return sshClient.CreateCommand(command).Execute();
}
示例3: ListenPort
/// <summary>
/// ListenPort
/// </summary>
/// <returns></returns>
public string ListenPort()
{
Constants.log.Info("Entering SshListener ListenPort Method!");
string response = string.Empty;
if (_sshClient == null && _connInfo == null)
{
Constants.log.Info("Calling SshListener InitializeListener Method!");
InitializeListener();
}
try
{
_sshClient = new SshClient(_connInfo);
_sshClient.Connect();
response = _sshClient.CreateCommand(this.Command).Execute();
}
catch (Exception ex)
{
Constants.log.Error(ex.Message);
response = ex.Message;
}
Constants.log.Info("Exiting SshListener ListenPort Method!");
return response;
}
示例4: Execute
//выполнение команд с новым клиентом
private void Execute(SshClient client, string command)
{
using (var cmd = client.CreateCommand(command))
{
cmd.Execute();
_listResult.Add(cmd.Result);
if (cmd.Error.Length != 0)
{
_listError.Add(cmd.Error);
}
}
}
示例5: Main
static void Main(string[] args)
{
string servers = ConfigurationManager.AppSettings["servers"];
string username = ConfigurationManager.AppSettings["username"];
string password = ConfigurationManager.AppSettings["password"];
foreach (string server in servers.Split(','))
{
ConnectionInfo ConnNfo = new ConnectionInfo(server, 22, username,
new AuthenticationMethod[]{
// Pasword based Authentication
new PasswordAuthenticationMethod(username,password)
}
);
string[] items = { "active_pwr", "energy_sum", "v_rms", "pf","enabled" };
using (var sshclient = new SshClient(ConnNfo))
{
Console.WriteLine("Connecting to {0}", server);
sshclient.Connect();
// quick way to use ist, but not best practice - SshCommand is not Disposed, ExitStatus not checked...
foreach (string itemName in items)
{
for (int port = 1; port < 7; port++)
{
string outputFileName = string.Format("{0}-{1}-{2}.txt", server, itemName, port);
Console.WriteLine(string.Format("{0}{1}", itemName, port));
string result = sshclient.CreateCommand(string.Format("cat /proc/power/{0}{1}", itemName, port)).Execute();
if (!File.Exists(outputFileName))
{
using (var writer = File.CreateText(outputFileName))
{
writer.WriteLine(string.Format("{0}, {1}", DateTime.Now.Ticks, result));
}
}
else
{
using (var writer = File.AppendText(outputFileName))
{
writer.WriteLine(string.Format("{0}, {1}", DateTime.Now.Ticks, result));
}
}
Console.WriteLine(result);
}
}
sshclient.Disconnect();
}
}
}
示例6: MakeRequest
public static string[] MakeRequest(SshClient client, string command)
{
SshCommand sshCommand = client.CreateCommand(command);
var asynch = sshCommand.BeginExecute();
StreamReader streamReader = new StreamReader(sshCommand.OutputStream);
string response = "";
while (!asynch.IsCompleted)
{
string result = streamReader.ReadToEnd();
if (result != "")
{
response += result;
}
}
return response.TrimEnd('\r', '\n').Split('\n');
}
示例7: Button_Click_3
private void Button_Click_3(object sender, RoutedEventArgs e)
{
Instellingen inst = new Instellingen();
ConnectionInfo connectionInfo = new PasswordConnectionInfo(inst.ip, "pi", "idpgroep5");
ssh = new SshClient(connectionInfo);
ssh.Connect();
var cmd = ssh.CreateCommand("./startSpinOS.sh"); // very long list
var asynch = cmd.BeginExecute();
System.Threading.Thread.Sleep(20000);
ssh.Disconnect();
/*SshStream ssh = new SshStream("192.168.10.1", "pi", "idpgroep5");
//Set the end of response matcher character
ssh.Prompt = "#";
//Remove terminal emulation characters
ssh.RemoveTerminalEmulationCharacters = true;
//Writing to the SSH channel
ssh.Write("./startSpinOS.sh");*/
}
示例8: SendCommand
/// <summary>
/// Sends a command with or without arguments to a remote SSH server, and then returns the response. (Ensure the response will be a single line with no required input!)
/// </summary>
/// <param name="address">The address to connect to</param>
/// <param name="username">The username to use to connect with</param>
/// <param name="password">The password for the username to connect to</param>
/// <param name="scriptName">The name of the script to run</param>
/// <param name="arguments">The arguments (if any) to send after the scriptName</param>
/// <returns>Either the response from the remote client (prefixed with 'P'), or the error that occurred (prefixed with 'F')</returns>
public static string SendCommand(string address, string username, string password, string scriptName, string arguments = "")
{
string response = string.Empty;
try
{
SshClient client = new SshClient(address, username, password);
client.Connect();
if (client.IsConnected)
{
SshCommand command = client.CreateCommand(string.Format("{0} {1}", scriptName, arguments));
command.Execute();
response = command.Result;
}
client.Disconnect();
client.Dispose();
}
catch (Exception exception)
{
return "F" + exception.Message; // F = Fail
}
return "P" + response; // P = Pass
}
示例9: BeginService
private void BeginService()
{
_client = new SshClient(Host, UserName, Password);
_client.Connect();
_client.RunCommand("sudo pkill mono");
var call = string.Format("cd {0}", _homePiBuildindicatronServer);
const string commandText = "sudo mono BuildIndicatron.Server.exe";
var text = call + " && " + commandText;
_log.Info("Starting command:" + text);
_runCommand = _client.CreateCommand(text);
_beginExecute = _runCommand.BeginExecute();
streamReader = new StreamReader(_runCommand.OutputStream);
WaitFor("Running", 6000).Wait();
}
示例10: GetCpuMemUsage
private IEnumerable<statistics> GetCpuMemUsage(SshClient client)
{
var pscmd = client.CreateCommand("ps ax -o %cpu,%mem,command |grep -v migration");
var cmdresult = pscmd.Execute();
var lines = cmdresult.Split(new char[] { '\r', '\n' }).Skip(1).ToList();
var infos = lines.Select(l =>
{
var data = l.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Where(s => s.Trim() != string.Empty)
.Select(s => { double d = 0; double.TryParse(s, out d); return d; }).ToList();
if (data.Count >= 2)
return new Tuple<double, double>(data[0], data[1]);
else
return new Tuple<double, double>(0, 0);
}).ToList();
var cpu = infos.Sum(d => d.Item1);
var mem = infos.Sum(d => d.Item2);
yield return new statistics()
{
type = StatisticsType.CPUUsage.ToString(),
val = cpu.ToString(),
};
yield return new statistics()
{
type = StatisticsType.MEMUsage.ToString(),
val = mem.ToString(),
};
}
示例11: OnRunCommand
/// <summary>
/// Runs a command on the specified PlanetLab node.
/// </summary>
/// <param name="state">The manager state.</param>
/// <param name="node">The PlanetLab node state.</param>
/// <param name="command">The PlanetLab command.</param>
/// <param name="set">The command parameter set.</param>
/// <param name="sshClient">The SSH client.</param>
private void OnRunCommand(PlManagerState state, PlManagerNodeState node, PlCommand command, int set, SshClient sshClient)
{
// Raise the command started event.
if (null != this.CommandStarted) this.CommandStarted(this, new PlManagerCommandEventArgs(state, node.Node, command, set));
try
{
// Compute the command text.
string commandText = set >= 0 ? command.GetCommand(set) : command.Command;
// The number of subcommands.
int success = 0;
int fail = 0;
// Divide the command into subcommands.
string[] subcommands = commandText.Split(PlManager.subcommandSeparators, StringSplitOptions.RemoveEmptyEntries);
// For all subcommands.
foreach (string subcommand in subcommands)
{
// If the operation has been paused, wait for resume.
if (state.IsPaused)
{
state.WaitPause();
}
// If the operation has been canceled, return.
if (state.IsStopped)
{
// Raise the canceled event.
if (null != this.CommandCanceled) this.CommandCanceled(this, new PlManagerCommandEventArgs(state, node.Node, command, set));
// Return.
return;
}
// If the subcommand is empty, continue to the next subcommand.
if (string.IsNullOrWhiteSpace(subcommand)) continue;
// Create a new SSH command.
using (SshCommand sshCommand = sshClient.CreateCommand(subcommand))
{
try
{
// The command duration.
TimeSpan duration;
// The retry count.
int retry = 0;
do
{
// The start time.
DateTime startTime = DateTime.Now;
// Execute the command.
sshCommand.Execute();
// Compute the command duration.
duration = DateTime.Now - startTime;
}
while ((retry++ < state.Slice.CommandRetries) && (sshCommand.ExitStatus != 0));
// Create a new command state.
PlManagerSubcommandState subcommandState = new PlManagerSubcommandState(node, sshCommand, duration, retry - 1);
// Increment the number of successful subcommands.
success++;
// Add the subcommand.
node.AddSubcommand(subcommandState);
// Raise a subcommand success event.
if (null != this.SubcommandSuccess) this.SubcommandSuccess(this, new PlManagerSubcommandEventArgs(state, node.Node, command, set, subcommandState));
}
catch (Exception exception)
{
// Create a new subcommand state.
PlManagerSubcommandState subcommandState = new PlManagerSubcommandState(node, sshCommand, exception);
// Increment the number of failed subcommands.
fail++;
// Add the subcommand.
node.AddSubcommand(subcommandState);
// Raise a subcommand fail event.
if (null != this.SubcommandFail) this.SubcommandFail(this, new PlManagerSubcommandEventArgs(state, node.Node, command, set, exception));
}
}
}
// Raise a command completed event.
if (null != this.CommandFinishedSuccess) this.CommandFinishedSuccess(this, new PlManagerCommandEventArgs(state, node.Node, command, set, success, fail));
}
catch (Exception exception)
//.........这里部分代码省略.........
示例12: MikrotikExportCompact
private string MikrotikExportCompact(string MikrotikIP, int MikrotikSSHPort, string MikrotikUser, string MikrotikPassword)
{
ConnectionInfo sLogin = new PasswordConnectionInfo(MikrotikIP, MikrotikSSHPort, MikrotikUser, MikrotikPassword);
SshClient sClient = new SshClient(sLogin);
sClient.Connect();
SshCommand appStatCmd = sClient.CreateCommand("export compact");
appStatCmd.Execute();
sClient.Disconnect();
sClient.Dispose();
return appStatCmd.Result;
}
示例13: GetVolInfo
private IEnumerable<statistics> GetVolInfo(SshClient client)
{
var cmdresult = client.CreateCommand("df -P").Execute();
var lines = cmdresult.Split(new char[] { '\r', '\n' });
var infos = lines
.Where(l => l.Trim().Length > 0)
.Select(l => l.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)).Skip(1);
foreach (var l in infos)
{
if (l[0].StartsWith("/dev") == false)
continue;
yield return new statistics()
{
type = StatisticsType.VolumeTotal.ToString(),
category = l[0],
val = l[1],
};
yield return new statistics()
{
type = StatisticsType.VolumeUsage.ToString(),
category = l[0],
val = l[2],
};
}
}
示例14: GetUpSeconds
private IEnumerable<statistics> GetUpSeconds(SshClient client)
{
var cmdresult = client.CreateCommand("cat /proc/uptime").Execute().Split(new char[] {' '});
double sec;
if (double.TryParse(cmdresult[0], out sec))
{
yield return new statistics()
{
type = StatisticsType.UpSeconds.ToString(),
val = sec.ToString(),
};
}
}
示例15: GetMemInfo
private IEnumerable<statistics> GetMemInfo(SshClient client)
{
var cmdresult = client.CreateCommand("cat /proc/meminfo").Execute();
var lines = cmdresult.Split(new char[] { '\r', '\n' });
var infos = lines.Select(l =>
{
var data = l.Split(new char[] { ':' });
if (data.Length == 2)
return new Tuple<string, string>(data[0], data[1]);
else
return new Tuple<string, string>(data[0], string.Empty);
}).ToDictionary(k => k.Item1);
Func<string, double> convertToDouble = str =>
{
if (str.EndsWith(" kB"))
return Convert.ToDouble(str.Substring(0, str.Length - 3))*1000;
else
return 0;
};
Tuple<string,string> d;
if (infos.TryGetValue("MemTotal", out d))
yield return new statistics()
{
type = StatisticsType.MemInfoTotal.ToString(),
val = convertToDouble(d.Item2).ToString(),
};
if (infos.TryGetValue("MemFree", out d))
yield return new statistics()
{
type = StatisticsType.MemInfoFree.ToString(),
val = convertToDouble(d.Item2).ToString(),
};
}