本文整理汇总了C#中Renci.SshNet.SshClient类的典型用法代码示例。如果您正苦于以下问题:C# SshClient类的具体用法?C# SshClient怎么用?C# SshClient使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
SshClient类属于Renci.SshNet命名空间,在下文中一共展示了SshClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: connect
private static void connect(string hostName, string userName, string password)
{
if (client != null && client.IsConnected)
return;
var connectionInfo = new KeyboardInteractiveConnectionInfo(hostName, userName);
connectionInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
{
foreach (var prompt in e.Prompts)
prompt.Response = password;
};
client = new SshClient(connectionInfo);
client.Connect();
sshStream = client.CreateShellStream("", 80, 40, 80, 40, 1024);
shellCommand("python", null);
using (var sr = new System.IO.StreamReader("queryJoints.py"))
{
String line;
while ((line = sr.ReadLine()) != null)
pythonCommand(line);
}
}
示例2: Main
static void Main(string[] args)
{
// Setup Credentials and Server Information
ConnectionInfo ConnNfo = new ConnectionInfo("10.141.3.110", 22, "root",
new AuthenticationMethod[]{
// Pasword based Authentication
new PasswordAuthenticationMethod("root","ismail"),
}
);
// 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("telnet localhost 6571");
Console.WriteLine("denemeeeeeee");
Console.WriteLine("deneme2");
//Console.WriteLine(sshclient.CreateCommand("cd /tmp && ls -lah").Execute());
//Console.WriteLine(sshclient.CreateCommand("pwd").Execute());
//Console.WriteLine(sshclient.CreateCommand("cd /tmp/uploadtest && ls -lah").Execute());
sshclient.Disconnect();
}
Console.ReadKey();
}
示例3: 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();
}
示例4: Main
static void Main(string[] args)
{
Console.WriteLine("fd");
try
{
ssh = new SshClient("10.141.3.110", "root", "ismail");
ssh.Connect();
//status = true;
//timer_enable();
}
//catch (Exception ex)
// {
// Console.Write(ex.Message);
//}
catch { }
if (true)
try
{
stream = ssh.CreateShellStream("xterm", 80, 50, 1024, 1024, 1024);
Thread.Sleep(100);
stream.WriteLine("telnet localhost 6571");
Thread.Sleep(100);
}
catch (Exception)
{
Console.WriteLine("hata");
}
Console.ReadKey();
}
示例5: ExecuteCommands
//выполнение списка команд
public override void ExecuteCommands(List<string> commands)
{
try
{
using (var sshclient = new SshClient(connInfo))
{
sshclient.Connect();
//если требуется привилегированный режим
if (_host.enableMode)
{
ExecuteEnableModeCommands(sshclient, commands);
}
//если не требуется привилегированный режим
else
{
foreach (string command in commands)
{
Execute(sshclient, command);
}
}
sshclient.Disconnect();
}
_success = true;
}
catch (Exception ex)//заменить на проброс исключения
{
_success = false;
_listError.Add(ex.Message);
}
}
示例6: LocalVmToolStripMenuItemClick
private void LocalVmToolStripMenuItemClick(object sender, EventArgs e)
{
var connectionInfo = new PasswordConnectionInfo(host, 22, username, password);
connectionInfo.AuthenticationBanner += ConnectionInfoAuthenticationBanner;
connectionInfo.PasswordExpired += ConnectionInfoPasswordExpired;
sshClient = new SshClient(connectionInfo);
sshClient.ErrorOccurred += SshClientErrorOccurred;
Log(string.Format("Connecting to {0}:{1} as {2}", connectionInfo.Host, connectionInfo.Port, connectionInfo.Username));
try
{
sshClient.Connect();
var tunnel = sshClient.AddForwardedPort<ForwardedPortLocal>("localhost", 20080, "www.google.com", 80);
tunnel.Start();
}
catch (Exception ex)
{
Log(ex.ToString());
}
finally
{
sshClient.Dispose();
}
Log("Connected");
sshClient.ForwardedPorts.ToList().ForEach(p => Log(string.Format("SSH tunnel: {0}:{1} --> {2}:{3}", p.BoundHost, p.BoundPort, p.Host, p.Port) ));
}
示例7: ButtonConnectClick
private void ButtonConnectClick(object sender, EventArgs e)
{
toolStripStatusLabel1.Text = "";
Application.DoEvents();
_client = new SshClient(textBoxIPAddr.Text, textBoxLogin.Text, textBoxPassword.Text);
_client.Connect();
toolStripStatusLabel1.Text = "Connection: " + _client.IsConnected;
Application.DoEvents();
bool stat;
string output;
var script = new Script(Globals.ScriptFileName);
script.Initialisation.SshClient = _client;
// script.Initialisation.OnUpdateUI -= testScript_OnUpdateUI;
// script.Initialisation.OnUpdateUI += testScript_OnUpdateUI;
stat = script.Initialisation.Execute(textBoxIPAddr.Text, textBoxLogin.Text,
textBoxPassword.Text, out output);
toolStripStatusLabel1.Text = "Copy status: " + stat;
}
示例8: SSHConnect
public static void SSHConnect()
{
string host = App.ViewModel.settings.SSHServerSetting;
int port = Convert.ToInt32(App.ViewModel.settings.SSHPortSetting);
string username = App.ViewModel.settings.SSHAccountSetting;
if (App.ViewModel.settings.SSHUseKeySetting)
{
string sshkey = App.ViewModel.settings.SSHKeySetting;
byte[] s = System.Text.Encoding.GetEncoding("iso-8859-1").GetBytes(sshkey);
MemoryStream m = new MemoryStream(s);
client = new SshClient(host, port, username, new PrivateKeyFile(m));
}
else
{
string password = App.ViewModel.settings.SSHPasswordSetting;
client = new SshClient(host, port, username, password);
}
System.Diagnostics.Debug.WriteLine("SSH client done");
client.Connect();
System.Diagnostics.Debug.WriteLine("SSH connect done");
}
示例9: Connect
public void Connect(string remoteIp, string username, string password)
{
sshClient = new SshClient(remoteIp, username, password);
scpClient = new ScpClient(remoteIp, username, password);
Connect();
}
示例10: Run
public override NodeResult Run()
{
if (string.IsNullOrEmpty(host.Value) || string.IsNullOrEmpty(user.Value) || string.IsNullOrEmpty(command.Value))
return NodeResult.Fail;
try
{
SshClient sshClient = new SshClient(host.Value, port.Value, user.Value, password.Value);
sshClient.Connect();
Renci.SshNet.SshCommand sshCommand = sshClient.RunCommand(command.Value);
Log.Info(sshCommand.CommandText);
if (!string.IsNullOrWhiteSpace(sshCommand.Result))
Log.Warning(sshCommand.Result);
if (!string.IsNullOrWhiteSpace(sshCommand.Error))
Log.Error(sshCommand.Error);
}
catch (Exception e)
{
Log.Error(e.Message);
return NodeResult.Fail;
}
return NodeResult.Success;
}
示例11: Execute
/// <summary>
/// Copy from source to target
/// </summary>
/// <returns></returns>
public override bool Execute(SshClient client)
{
Debug.WriteLine("CopyCommand");
var scp = new ScpClient(client.ConnectionInfo) {BufferSize = 8*1024};
Debug.WriteLine("Connect");
// Need this or we get Dropbear exceptions...
scp.Connect();
Debug.WriteLine("Upload");
bool status = false;
try
{
scp.Upload(new FileInfo(Source), Target);
status = true;
} catch(Exception e)
{
Logger.Warn("Exception in SCP transfer: " + e.Message);
}
Debug.WriteLine("Done");
return status;
}
示例12: Run
public void Run(string cmd, string host)
{
try
{
using (SshClient c = new SshClient(host, m_userName, m_userPassword))
{
Log.DebugFormat("Connecting to {0} with command: {1}", host, cmd );
c.Connect();
SshCommand ssh = c.RunCommand(cmd);
ExitStatus = ssh.ExitStatus;
Result = ssh.Result;
c.Disconnect();
if (Result.Length == 0)
{
Log.DebugFormat("Disconnecting from {0} with exit status: {1} (result is empty)", host, ExitStatus );
}
else
{
Log.DebugFormat("Disconnecting from {0} with exit status {1} result is: " + Environment.NewLine + "{2}", host, ExitStatus, Result);
}
}
}
catch (Exception ex)
{
Log.ErrorFormat("Failed to connect to {0} because: {1}", host, ex);
ExitStatus = -1;
Result = null;
}
}
示例13: Execute
/// <summary>
/// Copy from source to target
/// </summary>
/// <returns></returns>
public override bool Execute(SshClient client)
{
bool success = false;
try
{
Debug.WriteLine("ExtractCommand");
var command1 = client.RunCommand("tar xzvf " + Target);
var s1 = command1.Result;
Output = s1;
var command2 = client.RunCommand("echo $?");
var s2 = command2.Result;
var arrRsp = s2.Split(new[] {"\n"}, StringSplitOptions.None);
if(arrRsp.Length > 0)
if (arrRsp[0] == "0")
success = true;
} catch(Exception e)
{
Logger.Warn("Exception extracting archive: " +e.Message);
}
return success;
}
示例14: DoSystemUniquePool
protected override IEnumerable<statistics> DoSystemUniquePool()
{
using (var client = new SshClient(host, userid, pass))
{
client.HostKeyReceived += (sender, e) => {
e.CanTrust = true;
};
client.Connect();
foreach (var stats in new IEnumerable<statistics>[] {
GetMemInfo(client),
GetCpuMemUsage(client),
GetVolInfo(client),
GetMachineType(client),
GetUpSeconds(client),
GetInterfaceIP(client),
GetDMI(client),
GetCPUCores(client),
})
{
foreach (var s in stats)
{
s.begintime = s.endtime = DateTime.Now;
yield return s;
}
}
client.Disconnect();
}
yield break;
}
示例15: SshFactory
public SshFactory(String host, String username, String password)
{
_connection = new SshClient(host, username, password);
_connection.Connect();
_sftp = new SftpClient(_connection.ConnectionInfo);
_sftp.Connect();
}