|
1 | 1 | Think this page is lacking? Help wanted! Click "Edit this page" at the bottom to begin contributing more examples.
|
2 | 2 |
|
| 3 | +Getting Started |
| 4 | +================= |
| 5 | + |
| 6 | +### Run a command |
| 7 | + |
| 8 | +Establish an SSH connection and run a command: |
| 9 | + |
| 10 | +```cs |
| 11 | +using (var client = new SshClient("sftp.foo.com", "guest", new PrivateKeyFile("path/to/my/key"))) |
| 12 | +{ |
| 13 | + client.Connect(); |
| 14 | + using SshCommand cmd = client.RunCommand("echo 'Hello World!'"); |
| 15 | + Console.WriteLine(cmd.Result); // "Hello World!\n" |
| 16 | +} |
| 17 | +``` |
| 18 | + |
3 | 19 | ### Upload and list files
|
4 | 20 |
|
| 21 | +SFTP Connection / Exchange |
| 22 | + |
5 | 23 | ```cs
|
6 | 24 | using (var client = new SftpClient("sftp.foo.com", "guest", "pwd"))
|
7 | 25 | {
|
@@ -44,23 +62,44 @@ string expectedFingerPrint = "LKOy5LvmtEe17S4lyxVXqvs7uPMy+yF79MQpHeCs/Qo";
|
44 | 62 | using (var client = new SshClient("sftp.foo.com", "guest", "pwd"))
|
45 | 63 | {
|
46 | 64 | client.HostKeyReceived += (sender, e) =>
|
47 |
| - { |
48 |
| - e.CanTrust = expectedFingerPrint.Equals(e.FingerPrintSHA256); |
49 |
| - }; |
| 65 | + { |
| 66 | + e.CanTrust = expectedFingerPrint.Equals(e.FingerPrintSHA256); |
| 67 | + }; |
50 | 68 | client.Connect();
|
51 | 69 | }
|
52 | 70 | ```
|
53 | 71 |
|
54 |
| -### Run a command |
| 72 | +### Open a Shell |
55 | 73 |
|
56 |
| -Establish an SSH connection and run a command: |
| 74 | +```cs |
| 75 | +using (var client = new SshClient("sftp.foo.com", "user", "password")) |
| 76 | +{ |
| 77 | + client.Connect(); |
| 78 | + using ShellStream shellStream = client.CreateShellStream("ShellName", 80, 24, 800, 600, 1024); |
| 79 | + client.Disconnect(); |
| 80 | +} |
| 81 | +``` |
| 82 | + |
| 83 | +### Switch to root with "su - root" |
57 | 84 |
|
58 | 85 | ```cs
|
59 |
| -using (var client = new SshClient("sftp.foo.com", "guest", new PrivateKeyFile("path/to/my/key"))) |
| 86 | +using (var client = new SshClient("sftp.foo.com", "user", "password")) |
60 | 87 | {
|
61 | 88 | client.Connect();
|
62 |
| - SshCommand cmd = client.RunCommand("echo 'Hello World!'"); |
63 |
| - Console.WriteLine(cmd.Result); // "Hello World!\n" |
| 89 | + using ShellStream shellStream = client.CreateShellStream("ShellName", 80, 24, 800, 600, 1024); |
| 90 | + // Get logged in and get user prompt |
| 91 | + string prompt = shellStream.Expect(new Regex(@"[$>]")); |
| 92 | + // Send command and expect password or user prompt |
| 93 | + shellStream.WriteLine("su - root"); |
| 94 | + prompt = shellStream.Expect(new Regex(@"([$#>:])")); |
| 95 | + // Check to send password |
| 96 | + if (prompt.Contains(":")) |
| 97 | + { |
| 98 | + // Send password |
| 99 | + shellStream.WriteLine("password"); |
| 100 | + prompt = shellStream.Expect(new Regex(@"[$#>]")); |
| 101 | + } |
| 102 | + client.Disconnect(); |
64 | 103 | }
|
65 | 104 | ```
|
66 | 105 |
|
|
0 commit comments