//выполнение списка команд 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); } }
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; } }
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; } } } } }
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(); }
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()); }
/// <summary> /// /// </summary> /// <returns></returns> public virtual bool Execute() { var decryptedPassword = EncrytionHelper.Decrypt(SshPassword); var client = new Renci.SshNet.SshClient(SshHost, SshLogin, decryptedPassword); client.Connect(); var termkvp = new Dictionary <TerminalModes, uint>(); termkvp.Add(TerminalModes.ECHO, 53); var shellStream = client.CreateShellStream("xterm", 80, 24, 800, 600, 1024, termkvp); if (IsRoot) { SwitchToRoot(decryptedPassword, shellStream); } WriteStream(Command, shellStream); var result = ReadStream(shellStream); _log.Information(result); _log.Success("Command Execute finished!"); client.Disconnect(); return(true); }
public void ExeSSH(Object s) { using (var conninfo = new PasswordConnectionInfo(ip, log, pass)) { // try Renci.SshNet.SshClient client = new Renci.SshNet.SshClient(conninfo); // conninfo.Timeout = TimeSpan.FromSeconds(50); try { client.Connect(); } catch (Exception ex) { } try { Renci.SshNet.ShellStream stream = client.CreateShellStream("ssh", 180, 324, 1800, 3600, 8000); foreach (string command in list) { stream.Write(command + "\n"); System.Threading.Thread.Sleep(5000); string temp_string = stream.Read(); // File.WriteAllText(path, temp_string, Encoding.UTF8); File.WriteAllText("C:/" + ip + ".txt", temp_string, Encoding.UTF8); System.Threading.Thread.Sleep(5000); } client.Disconnect(); } catch (Exception ex) { } } }
public static String getPath(String username, String password, String host) { var ssh = new Renci.SshNet.SshClient(host, username, password); try { ssh.Connect(); } catch (Exception error) { Console.WriteLine("Couldn't connect to iPhone"); } if (ssh.IsConnected) { Console.WriteLine("\nConnected to iPhone (" + host + ")"); } else { Console.WriteLine("Could't connect to iPhone"); } Console.WriteLine("\nfind /var/mobile/Containers -iname pw.dat"); var cmd = ssh.CreateCommand("find /var/mobile/Containers -iname pw.dat"); // very long list var asynch = cmd.BeginExecute(delegate(IAsyncResult ar) { Console.WriteLine("\nDisconnected from iPhone."); }, null); var reader = new StreamReader(cmd.OutputStream); String output = ""; while (!asynch.IsCompleted) { var result = reader.ReadToEnd(); if (string.IsNullOrEmpty(result)) { continue; } Console.Write("\n> " + result); output = result; } cmd.EndExecute(asynch); String path = output.Substring(0, 76); Console.WriteLine(path); reader.Close(); ssh.Disconnect(); return(path); }
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(); } }
private void connBtn_Click(object sender, EventArgs e) { if (checkBox1.Checked) { sshconn = true; try { using (var client = new SshClient(hostTxt.Text, uidTxt.Text, passwordTxt.Text)) { client.Connect(); client.Disconnect(); MessageBox.Show("logged in!"); } LuiceEditor editor = new LuiceEditor(this); editor.Show(); } catch { MessageBox.Show("error: check again the data that you inserted and retry."); } } else { sshconn = false; string connection1 = "Server=" + hostTxt.Text + ";Port=" + portTxt.Text + ";Database=" + authTxt.Text + ";UID=" + uidTxt.Text + ";Password="******";"; string connection2 = "Server=" + hostTxt.Text + ";Port=" + portTxt.Text + ";Database=" + charTxt.Text + ";UID=" + uidTxt.Text + ";Password="******";"; string connection3 = "Server=" + hostTxt.Text + ";Port=" + portTxt.Text + ";Database=" + worldTxt.Text + ";UID=" + uidTxt.Text + ";Password="******";"; MySqlConnection conn1 = new MySqlConnection(connection1); MySqlConnection conn2 = new MySqlConnection(connection2); MySqlConnection conn3 = new MySqlConnection(connection3); try { //this is needed only to check if inserted data is correct conn1.Open(); conn2.Open(); conn3.Open(); //closing test connections conn1.Close(); conn2.Close(); conn3.Close(); MessageBox.Show("logged in!"); //passing method from form1 to LuiceEditor Form LuiceEditor editor = new LuiceEditor(this); editor.Show(); } catch { MessageBox.Show("error: check again the data that you inserted and retry."); } } }
static void _main() { BlackCore.basic.cParams args = bcore.app.args; client = new System.Net.Sockets.TcpClient(); int wavInDevices = WaveIn.DeviceCount; int selWav = 0; for (int wavDevice = 0; wavDevice < wavInDevices; wavDevice++) { WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(wavDevice); Console.WriteLine("Device {0}: {1}, {2} channels", wavDevice, deviceInfo.ProductName, deviceInfo.Channels); } Console.Write("Select device: "); selWav = int.Parse(Console.ReadLine()); Console.WriteLine("Selected device is " + selWav.ToString()); sshClient = new SshClient(args["host"], args["user"], args["pass"]); sshClient.Connect(); if (sshClient.IsConnected) { shell = sshClient.CreateShellStream("xterm", 50, 50, 640, 480, 17640); Console.WriteLine("Open listening socket..."); shell.WriteLine("nc -l " + args["port"] + "|pacat --playback"); System.Threading.Thread.Sleep(2000); Console.WriteLine("Try to connect..."); client.Connect(args["host"], int.Parse(args["port"])); if (!client.Connected) return; upStream = client.GetStream(); //==================== WaveInEvent wavInStream = new WaveInEvent(); wavInStream.DataAvailable += new EventHandler<WaveInEventArgs>(wavInStream_DataAvailable); wavInStream.DeviceNumber = selWav; wavInStream.WaveFormat = new WaveFormat(44100, 16, 2); wavInStream.StartRecording(); Console.WriteLine("Working....."); Console.ReadKey(); sshClient.Disconnect(); client.Close(); wavInStream.StopRecording(); wavInStream.Dispose(); wavInStream = null; } }
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"; } }
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(); } } }
public object Bootstrap(Drone drone) { using (var ssh = new SshClient(ChefHost, "root", "0953acb")) { ssh.Connect(); var cmd = ssh.RunCommand(string.Format("knife bootstrap {0} -x root -P 0953acb --sudo -N {1} --run-list speedymailer-drone -E xomixfuture", drone.Id, Guid.NewGuid().ToString().Replace("-", ""))); // very long list ssh.Disconnect(); return new { Drone = drone, Data = cmd.Result.Replace("\n", "<br>") }; } }
//Same as returnSSH, but specific a specific server isntead of a the generic RPI server public string returnSSHFrom(string passedCommand, string passedServer) { SshClient AuthClient = new SshClient(passedServer, username, password); try { AuthClient.Connect(); SshCommand RunCommand = AuthClient.RunCommand(passedCommand); AuthClient.Disconnect(); return RunCommand.Result; } catch { return ""; } }
private string username = ""; //private store for username and password #endregion Fields #region Methods //Use stored infor to run comamnds on a server public string returnSSH(string passedCommand) { SshClient AuthClient = new SshClient("rcs.rpi.edu", username, password); try { AuthClient.Connect(); SshCommand RunCommand = AuthClient.RunCommand(passedCommand); AuthClient.Disconnect(); return RunCommand.Result; } catch { return ""; } }
public void Disconnect() { if (thr != null) { thr.Abort(); thr = null; } if (sshClient != null) { if (sshClient.IsConnected) { sshClient.Disconnect(); } sshClient.Dispose(); } }
protected void RebootButton_Click(object sender, EventArgs e) { try { using (var client = new SshClient("ra-jetson.duckdns.org", "ubuntu", "savingL1v3s")) { client.Connect(); client.RunCommand("sudo /home/ubuntu/Desktop/bandhan/SQL-Scripts/./RightAlertRemoteRebootIssued-SQL"); // SSH Command Here client.RunCommand("sudo reboot"); // SSH Command Here client.Disconnect(); } } catch (Exception ex) { Response.Redirect("Down.html"); } }
public void StartService() { using (_client) { if (!_client.IsConnected) { _client.Connect(); } Console.WriteLine(_client.ConnectionInfo.ClientVersion); InitPortWorwarding(); Console.WriteLine(@"Press any key to shutdown..."); Console.ReadKey(); _client.Disconnect(); } }
//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 } }
private string SshExec(ResourceNode node, string command, string args = "") { lock (_lock) { int sshResult = 0; string sshOut = ""; string sshErr = ""; string sshCommand = command + " " + args; var sshExec = new Ssh2 .SshClient(node.NodeAddress, node.Credentials.Username, node.Credentials.Password); //.SshExec(node.NodeAddress, node.Credentials.Username, node.Credentials.Password); try { sshExec.Connect(); //sshResult = sshExec.RunCommand(sshCommand, ref sshOut, ref sshErr); var ssh = sshExec.RunCommand(sshCommand); ssh.Execute(); sshResult = ssh.ExitStatus; sshErr = ssh.Error; sshOut = ssh.Result; } catch (Exception e) { Log.Warn(e.Message); throw; } finally { if (sshExec.IsConnected) { sshExec.Disconnect(); } } sshErr = sshErr.Replace('.', ' '); // Cert creation emits many dots if (!String.IsNullOrWhiteSpace(sshErr)) { throw new Exception(String.Format("Ssh execution error. Command: \"{0}\". Code: {1}, StdOut: {2}, StdErr: {3}", sshCommand, sshResult, sshOut, sshErr)); } return(sshOut); } }
//выполнение команды public override void ExecuteCommand(string command) { try { using (var sshclient = new SshClient(connInfo)) { sshclient.Connect(); Execute(sshclient, command); sshclient.Disconnect(); } _success = true; } catch (Exception ex)//заменить на проброс исключения { _success = false; _listError.Add(ex.Message); } }
public String UploadFileToFtp(string url, string filePath) { try { var fileName = Path.GetFileName(filePath); Console.WriteLine(url); var request = (FtpWebRequest)WebRequest.Create(url + fileName); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential("cloudera", "cloudera"); request.UsePassive = true; request.UseBinary = true; request.KeepAlive = false; using (var fileStream = File.OpenRead(filePath)) { using (var requestStream = request.GetRequestStream()) { fileStream.CopyTo(requestStream); requestStream.Close(); } } var response = (FtpWebResponse)request.GetResponse(); response.Close(); Console.WriteLine("Subiendo archivo a hadoop"); using (var client = new SshClient("192.168.1.6", "cloudera", "cloudera")) { client.Connect(); client.RunCommand("hadoop fs -copyFromLocal JSON/" + fileName + " /user/JSON/"+fileName); client.RunCommand("rm JSON/" + fileName); client.Disconnect(); } return "Archivo Subido con éxito"; } catch (Exception ex) { return "Parece que tenemos un problema." + ex.Message; } }
public static string SendCommand(string address, string username, string password, string scriptName, string scriptArguments) { try { SshClient client = new SshClient(address, username, password); client.Connect(); if (client.IsConnected) { client.RunCommand(scriptName + " " + scriptArguments); } client.Disconnect(); } catch (Exception e) { return e.Message; } return null; }
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");*/ }
public List <CommandResult> ExecuteCommands(List <string> commands, ILog log) { var results = new List <CommandResult>(); var connectionInfo = GetConnectionInfo(_config); using (var ssh = new Renci.SshNet.SshClient(connectionInfo)) { try { ssh.Connect(); foreach (var command in commands) { try { var cmd = ssh.RunCommand(command); results.Add(new CommandResult { Command = command, Result = cmd.Result, IsError = false }); } catch (Exception exp) { results.Add(new CommandResult { Command = command, Result = exp.ToString(), IsError = true }); break; } } ssh.Disconnect(); } catch (Exception e) { log?.Error($"SShClient :: Error executing command {e}"); } } return(results); }
private bool ValidateCredentials(string username, string password, string serverip, int serverport) { if (username != null && password != null && serverip != null && serverport != 0) { try { using (var sshClient = new SshClient(serverip, serverport, username, password)) { sshClient.Connect(); sshClient.Disconnect(); } return true; } catch (Exception) { MessageBox.Show("The information was not valid.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return false; } } return false; }
public void ExSSH(string ip, string log, string pass, List <String> list) { // foreach (string ipadd in ip) // { using (var conninfo = new PasswordConnectionInfo(ip, log, pass)) { Renci.SshNet.SshClient client = new Renci.SshNet.SshClient(conninfo); client.Connect(); Renci.SshNet.ShellStream stream = client.CreateShellStream("ssh", 180, 324, 1800, 3600, 8000); foreach (string command in list) { // var command = "show config modified"; stream.Write(command + "\n"); System.Threading.Thread.Sleep(10000); string temp_string = stream.Read(); // Console.Write(temp_string); File.WriteAllText("C:/" + ip + " thread n- " + System.Threading.Thread.CurrentThread.ManagedThreadId + ".txt", temp_string, Encoding.UTF8); // System.Threading.Thread.Sleep(5000); } client.Disconnect(); // } } }
protected void LoginControl_Authenticate(object sender, AuthenticateEventArgs e) { bool authenticated = this.ValidateCredentials(LoginControl.UserName, LoginControl.Password); /// UPDATE ACtIVITY FEED WITH LOGON if (authenticated) { FormsAuthentication.RedirectFromLoginPage(LoginControl.UserName, LoginControl.RememberMeSet); try { using (var client = new SshClient("ra-jetson.duckdns.org", "ubuntu", "savingL1v3s")) { client.ConnectionInfo.RetryAttempts = 1; client.Connect(); client.RunCommand("sudo /home/ubuntu/Desktop/bandhan/SQL-Scripts/./UserLogon-SQL " + LoginControl.UserName.Trim().ToLower()); // SSH Command Here client.Disconnect(); } } catch (Exception ex) { Response.Redirect("~/Down.html"); } } }
/// <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 void backgroundWorkerConnect_DoWork(object sender, DoWorkEventArgs e) { try { Connection = new SshClient(_ip.ToString(), Settings.Default.DefaultPort, "pi", "raspberry"); Connection.Connect(); var c = Connection.RunCommand("cat /boot/customizer.txt"); c.Execute(); if (String.IsNullOrEmpty(c.Error)) { Configuration = c.Result; } else { e.Result = c.Error; Connection.Disconnect(); } } catch { } }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { try { using (var sshClient = new SshClient(SERVER_IP, SERVER_PORT, SERVER_USERNAME, SERVER_PASSWORD)) { sshClient.Connect(); toolStripStatusLabel1.Text = "Connected"; SshCommand cmd; ComboboxItem selectedItem = (ComboboxItem)e.Argument; if (selectedItem.Name == "Default Quality") { cmd = sshClient.CreateCommand(string.Format("youtube-dl --no-mtime --output '/var/www/html/%(title)s-%(id)s.%(ext)s' {0}", textBox_link.Text)); } else { cmd = sshClient.CreateCommand(string.Format("youtube-dl -f {0} --output '/var/www/html/%(title)s-%(id)s.%(ext)s' {1}", selectedItem.Value, textBox_link.Text)); } toolStripStatusLabel1.Text = "Preparing to download"; var async = cmd.BeginExecute(null, null); var reader = new StreamReader(cmd.OutputStream); while (!async.IsCompleted) { Thread.Sleep(100); var result = reader.ReadLine(); if (string.IsNullOrEmpty(result)) { continue; } toolStripStatusLabel1.Text = result; if (result.Contains("Destination")) { Video = (string)((string)result.Split(':').GetValue(1)).Split('/').GetValue(4); } if (result.Contains("has already been downloaded")) { Video = result; int a = result.IndexOf("has already been downloaded"); Video = (string)result.Substring(12, result.IndexOf("has already been downloaded") - 12).Split('/').GetValue(3); } } cmd.EndExecute(async); sshClient.Disconnect(); toolStripStatusLabel1.Text = "Transfer to server completed."; } } catch (Exception) { toolStripStatusLabel1.Text = "Error occurred!"; } }
public void Stop() { sshC.Disconnect(); }
private static void disconnectSSH(SshClient client) { ConsoleLogStartAction(Resources.UILogging.DisconnectSSH); client.Disconnect(); ConsoleEndAction(); }
private void btnUnixDetect_Click(object sender, RoutedEventArgs e) { try { var KeyboardInteractive = new Ssh.KeyboardInteractiveAuthenticationMethod(Host.Username); var Password = new Ssh.PasswordAuthenticationMethod(Host.Username, AES.DecryptString(Host.Password)); var encryptedPassword = Host.Password; KeyboardInteractive.AuthenticationPrompt += delegate(object sender1, Ssh.Common.AuthenticationPromptEventArgs e1) { foreach (var prompt in e1.Prompts) { if (prompt.Request.ToLower().Contains("password")) { prompt.Response = AES.DecryptString(encryptedPassword); } } }; var conn = new Ssh.ConnectionInfo(Host.Value, Host.Username, Password, KeyboardInteractive); using (Ssh.SshClient client = new Ssh.SshClient(conn)) { client.Connect(); var termdic = new Dictionary <Ssh.Common.TerminalModes, uint>(); termdic.Add(Ssh.Common.TerminalModes.ECHO, 0); using (var shell = client.CreateShellStream("gogrid", 80, 24, 800, 600, 1024, termdic)) { using (var output = new StreamReader(shell)) using (var input = new StreamWriter(shell)) { input.AutoFlush = true; while (shell.Length == 0) { Thread.Sleep(500); } //shell.WriteLine("stty raw -echo"); // disable echo while (shell.Length != 0) { shell.Read(); } shell.Write("([ -d ~/oraInventory/ContentsXML/ ] && [ -e ~/oraInventory/ContentsXML/inventory.xml ]) && echo epmi1 || echo epmi0\n"); while (shell.Length == 0) { Thread.Sleep(500); } var resp = shell.ReadLine(); while (shell.Length != 0) { shell.Read(); } if (System.Text.RegularExpressions.Regex.IsMatch(resp, "epmi1$")) { shell.Write("cat ~/oraInventory/ContentsXML/inventory.xml\n"); while (shell.Length == 0) { Thread.Sleep(500); } resp = Read(output, true); XmlDocument doc = new XmlDocument(); doc.LoadXml(resp); var nodes = doc.SelectNodes("INVENTORY/HOME_LIST/HOME"); for (int i = 0; i < nodes.Count; i++) { if (Regex.IsMatch(nodes[i].Attributes["NAME"].Value, @"EpmSystem_\S+")) { tbxUnixPath.Text = nodes[i].Attributes["LOC"].Value; break; } } MessageBox.Show("Success"); } } } client.Disconnect(); } } catch (Ssh.Common.SshAuthenticationException) { MessageBox.Show("Failed to authenticate to server. Check username and password."); } catch (Exception) { MessageBox.Show("Unknown error."); } }
public bool ExecuteNetworkDeviceCommand(DeviceViewModel deviceViewModel, string commandText, bool unattended = false) { NetworkDevices.NetworkDevice networkDevice = GetNetworkDeviceByPath(deviceViewModel.Path); string username = networkDevice.Username; string password = networkDevice.Password; string devicePath = deviceViewModel.Path; string deviceName = devicePath; if (!String.IsNullOrEmpty(deviceViewModel.FriendlyName)) deviceName = deviceViewModel.FriendlyName; bool success = false; bool stop = false; bool prompt = String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password); if (unattended && prompt) return false; while (!success && !stop) { if (prompt) { CredentialsEventArgs ea = new CredentialsEventArgs { ProtectedResource = deviceName, Username = username, Password = password }; if (CredentialsRequested != null) CredentialsRequested(this, ea); if (ea.CredentialsProvided) { username = ea.Username; password = ea.Password; } else { stop = true; } } if (!stop) { Uri uri = new Uri("http://" + devicePath); using (SshClient client = new SshClient(uri.Host, username, password)) { try { client.Connect(); } catch (Exception ex) { if (ex is SshAuthenticationException) prompt = true; else if ((ex is SocketException) || (ex is SshOperationTimeoutException)) { stop = true; PostNotification(String.Format("{0}: {1}", deviceName, ex.Message), NotificationKind.Danger); } else throw; } if (client.IsConnected) { try { stop = true; success = ExecuteSshCommand(deviceName, client, commandText); } finally { client.Disconnect(); } } } } } if (success) { networkDevice.Username = username; networkDevice.Password = password; NetworkDevicesConfiguration.SaveNetworkDevicesConfiguration(); } return success; }
/// <summary> /// Disconnects client from the server. /// </summary> public void Disconnect() { _sshClient.Disconnect(); }
private void gothroughlinux(string c, string username, string password) { System.Threading.Tasks.Task task_1 = new System.Threading.Tasks.Task(() => { try { using (var client = new SshClient(c, username, password)) { try { string list_mftr = ""; string list_hw = ""; string list_sn = ""; long list_mem = 0; string list_os = ""; string list_osver = ""; string list_osmftr = ""; string list_osserial = ""; string list_osverno = ""; string list_cpucount = ""; string list_cpucore = ""; string list_cpuspeed = ""; bool not_has = true; client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(5); client.Connect(); var device_name = client.CreateCommand("/bin/hostname"); device_name.CommandTimeout = TimeSpan.FromSeconds(2); device_name.Execute(); string dev_name = device_name.Result.Trim(); if (ignoreDomain.Checked) { dev_name = dev_name.Split('.')[0]; } foreach (string[] subList in all_the_values) { if (subList[0] == dev_name) { not_has = false; break; } } if (not_has) { var release = client.CreateCommand("/usr/bin/python -m platform"); release.CommandTimeout = TimeSpan.FromSeconds(2); release.Execute(); string prfx = ""; if (username != "root") { prfx = "sudo "; } var manufacturer = client.CreateCommand(prfx + "/usr/sbin/dmidecode -s system-manufacturer"); manufacturer.CommandTimeout = TimeSpan.FromSeconds(2); manufacturer.Execute(); var hardware = client.CreateCommand(prfx + "/usr/sbin/dmidecode -s system-product-name"); hardware.CommandTimeout = TimeSpan.FromSeconds(2); hardware.Execute(); var serial_no = client.CreateCommand(prfx + "/usr/sbin/dmidecode -s system-serial-number"); serial_no.CommandTimeout = TimeSpan.FromSeconds(2); serial_no.Execute(); var ifconfig = client.CreateCommand("/sbin/ifconfig -a | grep -A 2 Ethernet"); ifconfig.CommandTimeout = TimeSpan.FromSeconds(2); ifconfig.Execute(); var meminfo = client.CreateCommand("grep MemTotal /proc/meminfo"); meminfo.CommandTimeout = TimeSpan.FromSeconds(2); meminfo.Execute(); var cpuinfo = client.CreateCommand(prfx + "/usr/sbin/dmidecode -s processor-frequency | grep MHz"); cpuinfo.CommandTimeout = TimeSpan.FromSeconds(2); cpuinfo.Execute(); var coreinfo = client.CreateCommand(prfx + "/usr/sbin/dmidecode -t processor | grep \"Core Count\" | head -1"); coreinfo.CommandTimeout = TimeSpan.FromSeconds(2); coreinfo.Execute(); client.Disconnect(); string os = Regex.Split(release.Result, "-with-")[1].Split('-')[0]; string osver = Regex.Split(release.Result, "-with-")[1].Split('-')[1]; //string osverno = Regex.Split(release.Result, "-with-")[0]; list_os = os; list_osver = osver; //list_osverno = osverno; string Mftr = manufacturer.Result.Trim().Replace("# SMBIOS implementations newer than version 2.6 are not\n# fully supported by this version of dmidecode.\n",""); string[] strArray = new string[] { "VMware, Inc.", "Bochs", "KVM", "QEMU", "Microsoft Corporation", "Xen" }; foreach (string m_s in strArray) { if (m_s == Mftr) { list_mftr = "virtual"; break; } } if (list_mftr != "virtual") { list_mftr = Mftr; list_hw = hardware.Result.Trim().Replace("# SMBIOS implementations newer than version 2.6 are not\n# fully supported by this version of dmidecode.\n", ""); list_sn = serial_no.Result.Trim().Replace("# SMBIOS implementations newer than version 2.6 are not\n# fully supported by this version of dmidecode.\n", ""); } string memory_total = meminfo.Result.Replace(" ", "").Replace("MemTotal:", "").Replace("kB", ""); long mem3 = upper_power_of_two(Convert.ToInt64(memory_total) / 1024); list_mem = mem3; int cpucount = 0; decimal cspeed = 0.0m; string cpuspeed = ""; using (StringReader reader = new StringReader(cpuinfo.Result)) { string line = string.Empty; do { line = reader.ReadLine(); if (line != null) { cpucount += 1; cpuspeed = Regex.Split(line, "MHz")[0].Trim(); cspeed = Convert.ToDecimal(cpuspeed) / 1000; } } while (line != null); } string cpucores = coreinfo.Result.Replace("Core Count: ", "").Trim(); if (cpucount > 0) { list_cpucount = cpucount.ToString(); list_cpuspeed = Convert.ToString(cspeed); if (cpucores != "") { list_cpucore = cpucores; } } all_the_values.Add(new string[] { dev_name, list_mftr, list_hw, list_sn, list_os, list_osver, list_osverno, list_osserial, list_osmftr, list_mem.ToString(), list_cpucount, list_cpucore, list_cpuspeed }); string[] ifaces = Regex.Split(ifconfig.Result, "--\n"); foreach (string iface in ifaces) { if (iface.Contains("inet addr")) { string[] line = Regex.Split(iface, "\n"); string ipv4_address = "", tag = "", mac = ""; foreach (string ln in line) { if (ln.Contains("inet addr")) { ipv4_address = ln.Split(':')[1].Split(' ')[0]; } if (ln.Contains("Ethernet")) { tag = ln.Split()[0]; mac = Regex.Split(ln, "HWaddr ")[1]; } } all_the_ip_values.Add(new string[] { ipv4_address, tag, mac, dev_name }); } if (iface.Contains("inet6 addr")) { string[] line = Regex.Split(iface, "\n"); string ipv6_address = "", tag = "", mac = ""; foreach (string ln in line) { if (ln.Contains("inet6 addr")) { ipv6_address = Regex.Split(ln, "addr: ")[1].Split('/')[0]; } if (ln.Contains("Ethernet")) { tag = ln.Split()[0]; mac = Regex.Split(ln, "HWaddr ")[1]; } } all_the_ip6_values.Add(new string[] { ipv6_address, tag, mac, dev_name }); } } } } catch (Exception ex) { //Console.WriteLine(ex.ToString()); client.Disconnect(); Trace.WriteLine(ex.ToString()); } } } catch (Exception ex) { Trace.WriteLine(ex.ToString()); } }, tokenSource.Token); task_1.Start(); task_1.ContinueWith(t => check_linux_progress()); }
private static object SendCommandToDrone(Drone drone, string commandText) { using (var ssh = new SshClient(drone.Id, "root", "0953acb")) { ssh.Connect(); var cmd = ssh.RunCommand(commandText); // very long list ssh.Disconnect(); if (cmd.ExitStatus > 0) return new { Drone = drone, Data = cmd.Result.Replace("\n", "<br>") }; return new { Drone = drone, Data = "OK" }; } }
/// <summary> /// Runs the commands on the PlanetLab node at the specified index. /// </summary> /// <param name="state">The state.</param> /// <param name="index">The node state index.</param> private void OnRunNode(PlManagerState state, int index) { lock (state.Sync) { // If the operation has been canceled, return. if (state.IsStopped) return; // Get the node state. PlManagerNodeState nodeState = state.GetNode(index); // Execute the secure shell connection on the thread pool. ThreadPool.QueueUserWorkItem((object threadState) => { // Raise a node started event. if (null != this.NodeStarted) this.NodeStarted(this, new PlManagerNodeEventArgs(state, nodeState.Node)); try { // Create the private key connection information. ConnectionInfo connectionInfo; // Create a memory stream with the key data. using (MemoryStream memoryStream = new MemoryStream(state.Slice.Key)) { // Create the private key file. using (PrivateKeyFile keyFile = new PrivateKeyFile(memoryStream)) { // Create a key connection info. connectionInfo = new PrivateKeyConnectionInfo(nodeState.Node.Hostname, state.Slice.Name, keyFile); } } // Open an SSH client to the PlanetLab node. using (SshClient sshClient = new SshClient(connectionInfo)) { // Connect the client. sshClient.Connect(); // For all the slice commands. foreach (PlCommand command in state.Slice.Commands) { // If the command has parameters. if (command.HasParameters) { // Format the command with all parameter sets. for (int indexSet = 0; indexSet < command.SetsCount; indexSet++) { // If the operation has been paused, wait for resume. if (state.IsPaused) { state.WaitPause(); } // If the operation has been canceled, return. if (state.IsStopped) { // Remove the node from the running list. state.UpdateNodeRunningToSkipped(index); // Cancel all nodes in the pending list. state.CancelPendingNodes(); // Raise the canceled event. if (null != this.NodeCanceled) this.NodeCanceled(this, new PlManagerNodeEventArgs(state, nodeState.Node)); // Return. return; } // Run the command with the current parameters set. this.OnRunCommand(state, nodeState, command, indexSet, sshClient); } } else { // Run the command without parameters. this.OnRunCommand(state, nodeState, command, -1, sshClient); } } // Disconnect the client. sshClient.Disconnect(); } // Remove the node from the running list. state.UpdateNodeRunningToCompleted(index); // Raise the success event. if (null != this.NodeFinishedSuccess) this.NodeFinishedSuccess(this, new PlManagerNodeEventArgs(state, nodeState.Node)); } catch (Exception exception) { // Remove the node from the running list. state.UpdateNodeRunningToSkipped(index); // Raise the fail event. if (null != this.NodeFinishedFail) this.NodeFinishedFail(this, new PlManagerNodeEventArgs(state, nodeState.Node, exception)); } finally { lock (state.Sync) { // If the operation has not been canceled. if (!state.IsStopped) { // If the list of pending nodes and running nodes is empty, stop. if ((0 == state.PendingCount) && (0 == state.RunningCount)) { this.Stop(state); } // Get a cached copy of all the pending PlanetLab nodes. int[] pendingCache = state.PendingNodes.ToArray(); // Find the next pending node to execute commands. foreach (int newIndex in pendingCache) { // Get the node state corresponding to the pending node. PlManagerNodeState newNode = state.GetNode(newIndex); // If the slice configuration only allows one node per site. if (state.Slice.OnlyRunOneNodePerSite) { // If the node site is completed. if (state.IsSiteCompleted(newNode.Node.SiteId.Value)) { // Change the node from the pending to the skipped state. state.UpdateNodePendingToSkipped(newIndex); // Raise an event indicating that the node has been skipped. if (null != this.NodeSkipped) this.NodeSkipped(this, new PlManagerNodeEventArgs(state, newNode.Node)); // Skip the loop to the next node. continue; } // If the node site is running. if (state.IsSiteRunning(newNode.Node.SiteId.Value)) { // Postpone the node for later, and skip the loop to the next node. continue; } } // Change the node from the pending to the running state. state.UpdateNodePendingToRunning(newIndex); // Execute the commands on specified node. this.OnRunNode(state, newIndex); // Exit the loop. break; } } } } }); } }
public void Startup() { while (keepstart) { start = new SshClient(host, user, pass); try { start.Connect(); start.RunCommand("sudo python3 control/CommandReader.py"); } catch { Console.Write("not wokring"); } } start.Disconnect(); }
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); }
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(); }