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) )); }
private void button1_Click(object sender, EventArgs e) { string host = textBoxServer.Text.Trim(); string userName = textBoxUserName.Text.Trim(); string psw = textBoxPassword.Text.Trim(); string url = textBoxCoomand.Text.Trim(); string location = @" -P " + textBoxLocation.Text.Trim(); string finalCommand = @"wget -bqc '" + url + "' " + location + " "; ConnectionInfo conInfo = new ConnectionInfo(host, 22, userName, new AuthenticationMethod[]{ new PasswordAuthenticationMethod(userName,psw) }); SshClient client = new SshClient(conInfo); try { client.Connect(); var outptu = client.RunCommand(finalCommand); } catch (Exception ex) { textBoxDisplay.Text = ex.Message; throw; } client.Disconnect(); client.Dispose(); SetLastValues(host, userName, psw, textBoxLocation.Text.Trim()); }
public void ConnectionTests(int count, int pause) { var regex = new Regex(@"^\d+\s[\d\w:]+\s[\d\.]+\s.+?\s.+?$", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Multiline); Renci.SshNet.SshClient client; { var path = Concrete.Client.FixPath(_config.PathToPrivateKey !); using var keyFile = new Renci.SshNet.PrivateKeyFile(path); client = new Renci.SshNet.SshClient(_config.Host, _config.Port, _config.Username, keyFile); } client.Connect(); while (count-- > 0) { string output; { using var command = client.CreateCommand("cat /tmp/dhcp.leases", Encoding.UTF8); command.CommandTimeout = TimeSpan.FromSeconds(1); output = command.Execute(); } Assert.NotNull(output); Assert.NotEmpty(output); Assert.Matches(regex, output); Thread.Sleep(pause); } client.Disconnect(); client.Dispose(); }
public void GetUsers(object sender, BackgroundWorker worker, Delegate sendUsers) { foreach (string host in SshSettings.Hosts()) { if (worker.CancellationPending) break; List<SshUser> users = new List<SshUser>(); using (SshClient ssh = new SshClient(_currentUser.GetPasswordConenctionInfo(String.Concat(host, SshSettings.Domain)))) { try { ssh.Connect(); string response = ssh.RunCommand("who -u").Execute(); // TODO: Parse response. ParseWhoResponse(response, host, ref users); if (users.Count > 0) ((System.Windows.Forms.Form) sender).Invoke(sendUsers, users); } catch (Exception ex) { if (ex is SshException || ex is SocketException) { if (ssh.IsConnected) ssh.Disconnect(); ssh.Dispose(); } else { throw; } } } } }
/// <summary> /// Dispose(bool disposing) executes in two distinct scenarios. /// If disposing equals true, the method has been called directly /// or indirectly by a user's code. Managed and unmanaged resources /// can be disposed. /// If disposing equals false, the method has been called by the /// runtime from inside the finalizer and you should not reference /// other objects. Only unmanaged resources can be disposed. /// </summary> protected virtual void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!this._disposed) { // Note disposing has been done. _disposed = true; // If disposing equals true, dispose all managed // and unmanaged resources. if (disposing) { if (_sshClient != null) { _sshClient.Dispose(); } if (_sshConnection != null) { _sshConnection.Dispose(); } } // Call the appropriate methods to clean up // unmanaged resources here. _sshClient = null; _sshConnection = null; } }
public void run(string host, string user, string pass, string command) { using (var sshClient = new SshClient(host, user, pass)) { sshClient.Connect(); sshClient.RunCommand(command); sshClient.Disconnect(); sshClient.Dispose(); } }
public void button1_Click(object sender, EventArgs e) { int port = int.Parse(userInputPort.Text); //Renci.SshNet.SshClient cSSH = new SshClient("192.168.10.144", 22, "root", "pacaritambo"); try { cSSH = new SshClient(userInputIP.Text, port, userInputUsername.Text, userInputPassword.Text); } catch (Exception ex) { printError(ex.ToString() + " happened in Renci.SshNet.SshClient"); return; } try { cSSH.Connect(); } catch (Exception ex) { printError(ex.ToString() + " happened in cSSH.Connect()"); return; } if (connected == true) { //disconnect statusLabel.ForeColor = Color.Red; statusLabel.Text = "Disconnected"; printInfo("Disconnected by user."); connected = false; buttonConnect.Text = "Connect to device"; cSSH.Disconnect(); cSSH.Dispose(); return; } if (connected == false) { //connect statusLabel.ForeColor = Color.DarkGreen; statusLabel.Text = "Connected"; printInfo("Successfully connected."); connected = true; buttonConnect.Text = "Disconnect from device"; } }
public void Disconnect() { if (thr != null) { thr.Abort(); thr = null; } if (sshClient != null) { if (sshClient.IsConnected) { sshClient.Disconnect(); } sshClient.Dispose(); } }
//Authenticate users public bool rpi_authent(string passedUsername, string passedPassword) { SshClient AuthClient = new SshClient("rcs.rpi.edu", passedUsername, passedPassword);//Using Renci try { AuthClient.Connect(); //try to connect AuthClient.Disconnect(); //If that worked disconnect AuthClient.Dispose(); //Clean up connection username = passedUsername; //Store data in private collection because it worked password = passedPassword; return true; } catch { return false; //This failed, either server is bad, but thats public so username and password are bad } }
/// <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 }
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; }
public void Dispose() { _sshClient?.Dispose(); _sftpClient?.Dispose(); _scpClient?.Dispose(); }
// Use this for initialization public void Send() { string address = "10.211.55.4"; string user = "******"; string pass = "******"; //string cmd = "r2 '/home/parallels/Desktop/Bomb.ex_' -c 'aa;s section..text;afn main;e asm.lines=False;e asm.comments=False;e asm.calls=false;e asm.cmtflgrefs=false;e asm.cmtright=false;e asm.flags=false;e asm.function=false;e asm.functions=false;e asm.vars=false;e asm.xrefs=false;e asm.linesout=false;e asm.fcnlines=false;e asm.fcncalls=false;e asm.demangle=false;aa;s section..text;pdf>main.txt;exit' -q"; string cmd = "r2 '/home/parallels/Desktop/Bomb.ex_' -c 'aa; s section..text; afn main; pdf @ main > main.txt' -q"; string uploadfile = @"/Users/JonathanWatts/Desktop/Bomb.ex_"; string uploadDirectory = "/home/parallels/Desktop/"; //Upload a file to a linux VM using (var sftp = new SftpClient(address, user, pass)) { try { sftp.Connect(); using (var fileStream = new FileStream(uploadfile, FileMode.Open)) { Console.WriteLine("Uploading {0} ({1:N0} bytes)", uploadfile, fileStream.Length); sftp.BufferSize = 4 * 1024; // bypass Payload error large files sftp.UploadFile(fileStream, uploadDirectory + Path.GetFileName(uploadfile)); } sftp.Disconnect(); sftp.Dispose(); } catch(Exception ex) { Console.WriteLine(ex.Message); } } //This block of code will send linux terminal commands from windows machine to linux virtual machine using(SshClient client = new SshClient(address,user, pass)) { try { Debug.Log ("Sending Command..."); client.Connect(); Debug.Log ("Sending Command..."); var result = client.RunCommand(cmd); Debug.Log (result); client.Disconnect(); Debug.Log ("Sending Command..."); client.Dispose(); } catch(Exception ex) { Debug.Log (ex.Message); Console.WriteLine(ex.Message); } } //This block of code will download the file from linux VM to the windows host machine try { Debug.Log ("Uploading file..."); using (var sftp = new SftpClient(address, user, pass)) { sftp.Connect(); if(File.Exists("/Users/JonathanWatts/main333.txt")) { File.Delete("/Users/JonathanWatts/main333.txt"); } using (Stream file1 = File.OpenWrite("/Users/JonathanWatts/main333.txt")) { try { sftp.DownloadFile("main.txt", file1); } catch (Exception ex) { Console.WriteLine(ex.Message); } file1.Close(); } sftp.Disconnect(); sftp.Dispose(); } } catch(Exception ex) { Debug.Log (ex.Message); Console.WriteLine(ex.Message); } //SshShell shell = new SshShell(address, user, pass); }
public void Dispose() { _client?.Dispose(); _forwardedPort?.Dispose(); }
static void Main(string[] args) { string address = "192.168.17.129"; string user = "******"; string pass = "******"; string cmd = "r2 '/home/swastik/Desktop/Bomb.ex_' -c 'aa;s section..text;pdf;pdi;e asm.lines=False;e asm.comments=False;e asm.calls=false;e asm.cmtflgrefs=fal;e asm.cmtright=false;e asm.flags=false;e asm.function=false;e asm.functions=fals;e asm.vars=false;e asm.xrefs=false;e asm.linesout=false;e asm.fcnlines=false;e asm.fcncalls=false;e asm.demangle=false;aa;s section..text;pdf>main.txt;exit' -q"; string uploadfile = @"C:\Users\Swastik\Google Drive\Research\Malaware Visualization\Tool\radare2-w32-0.9.9-git\Bomb.ex_"; string uploadDirectory = "/home/swastik/Desktop/"; //Upload a file to a linux VM using (var sftp = new SftpClient(address, user, pass)) { try { sftp.Connect(); using (var fileStream = new FileStream(uploadfile, FileMode.Open)) { Console.WriteLine("Uploading {0} ({1:N0} bytes)", uploadfile, fileStream.Length); sftp.BufferSize = 4 * 1024; // bypass Payload error large files sftp.UploadFile(fileStream, uploadDirectory + Path.GetFileName(uploadfile)); } sftp.Disconnect(); sftp.Dispose(); } catch(Exception ex) { Console.WriteLine(ex.Message); } } //This block of code will send linux terminal commands from windows machine to linux virtual machine using(SshClient client = new SshClient(address,user, pass)) { try { client.Connect(); var result = client.RunCommand(cmd); client.Disconnect(); client.Dispose(); } catch(Exception ex) { Console.WriteLine(ex.Message); } } //This block of code will download the file from linux VM to the windows host machine try { using (var sftp = new SftpClient(address, user, pass)) { sftp.Connect(); using (Stream file1 = File.OpenWrite("d:\\main333.txt")) { try { sftp.DownloadFile("main.txt", file1); } catch (Exception ex) { Console.WriteLine(ex.Message); } file1.Close(); } sftp.Disconnect(); sftp.Dispose(); } } catch(Exception ex) { Console.WriteLine(ex.Message); } //SshShell shell = new SshShell(address, user, pass); }