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); } }
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(); }
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(); }
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) )); }
//выполнение списка команд 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); } }
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; }
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(); }
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(); }
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 SshFactory(String host, String username, String password) { _connection = new SshClient(host, username, password); _connection.Connect(); _sftp = new SftpClient(_connection.ConnectionInfo); _sftp.Connect(); }
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) { } } }
/// <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; }
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; }
private static String ExecuteCommand(SshClient sshClient, String command) { if (!sshClient.IsConnected) sshClient.Connect(); return sshClient.CreateCommand(command).Execute(); }
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; }
/// <summary> /// Open a Connection to the cloudera /// </summary> private void OpenConnecion() { sshClient = new SshClient(hostname, userName, password); sshClient.Connect(); scpClient = new ScpClient(hostname, userName, password); scpClient.Connect(); }
private static void connectSSH(SshClient client) { ConsoleLogStartAction(Resources.UILogging.ConnectSSH); client.Connect(); ConsoleEndAction(); }
private void Connect() { if (_connected) return; _client = new SshClient(_con); _client.Connect(); _ports = new List<ForwardedPortLocal>(); _connected = true; }
public void Connect() { sshClient.Connect(); ss = sshClient.CreateShellStream(Host, 10, 10, 10, 10, 1024); thr = new Thread(thrRead); thr.Start(); }
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."); } } }
public void beginCracking() { log("beginning cracking process.."); var connectionInfo = new PasswordConnectionInfo (xml.Config.host, xml.Config.port, "root", xml.Config.Password); using (var sftp = new SftpClient(connectionInfo)) { using (var ssh = new SshClient(connectionInfo)) { PercentStatus("Establishing SSH connection", 5); ssh.Connect(); PercentStatus("Establishing SFTP connection", 10); sftp.Connect(); log("Cracking " + ipaInfo.AppName); PercentStatus("Preparing IPA", 25); String ipalocation = AppHelper.extractIPA(ipaInfo); using (var file = File.OpenRead(ipalocation)) { log("Uploading IPA to device.."); PercentStatus("Uploading IPA", 40); sftp.UploadFile(file, "Upload.ipa"); } log("Cracking! (This might take a while)"); PercentStatus("Cracking", 50); String binaryLocation = ipaInfo.BinaryLocation.Replace("Payload/", ""); String TempDownloadBinary = Path.Combine(AppHelper.GetTemporaryDirectory(), "crackedBinary"); var crack = ssh.RunCommand("Clutch -i 'Upload.ipa' " + binaryLocation + " /tmp/crackedBinary"); log("Clutch -i 'Upload.ipa' " + binaryLocation + " /tmp/crackedBinary"); log("cracking output: " + crack.Result); using (var file = File.OpenWrite(TempDownloadBinary)) { log("Downloading cracked binary.."); PercentStatus("Downloading cracked binary", 80); try { sftp.DownloadFile("/tmp/crackedBinary", file); } catch (SftpPathNotFoundException e) { log("Could not find file, help!!!!!"); return; } } PercentStatus("Repacking IPA", 90); String repack = AppHelper.repack(ipaInfo, TempDownloadBinary); PercentStatus("Done!", 100); log("Cracking completed, file at " + repack); } } }
private static MyAsyncInfo info; // unique class containing information obtained from an asynchronous read // constructor that initializes the client object and creates a connection to the remote terminal public SSH(string IP, string user, string pass) { // initilizes client object containing server information client = new SshClient(IP, user, pass); // connects to the server client.Connect(); // creates a stream to communicate with the remote terminal stream = client.CreateShellStream(@"xterm", 80, 24, 800, 600, 2048); }
public static void flash_px4(string firmware_file) { if (is_solo_alive) { using (SshClient client = new SshClient("10.1.1.10", 22, "root", "TjSDBkAu")) { client.KeepAliveInterval = TimeSpan.FromSeconds(5); client.Connect(); if (!client.IsConnected) throw new Exception("Failed to connect ssh"); var retcode = client.RunCommand("rm -rf /firmware/loaded"); using (ScpClient scpClient = new ScpClient(client.ConnectionInfo)) { scpClient.Connect(); if (!scpClient.IsConnected) throw new Exception("Failed to connect scp"); scpClient.Upload(new FileInfo(firmware_file), "/firmware/" + Path.GetFileName(firmware_file)); } var st = client.CreateShellStream("bash", 80, 24, 800, 600, 1024*8); // wait for bash prompt while (!st.DataAvailable) System.Threading.Thread.Sleep(200); st.WriteLine("loadPixhawk.py; exit;"); st.Flush(); StringBuilder output = new StringBuilder(); while (client.IsConnected) { var line = st.Read(); Console.Write(line); output.Append(line); System.Threading.Thread.Sleep(100); if (output.ToString().Contains("logout")) break; } } } else { throw new Exception("Solo is not responding to pings"); } }
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"; } }
public static bool TestCredentials(PasswordConnectionInfo connectionInfo) { bool connected = false; using (SshClient ssh = new SshClient(connectionInfo)) { try { ssh.Connect(); connected = ssh.IsConnected; } catch (SshAuthenticationException) { connected = false; } } return connected; }
public void Connect() { PluginConfigurationEntity configuration; using (var gateway = GlobalConfigurationGatewayFactory()) { configuration = gateway.GetGlobalConfiguration(); } var keyStream = new MemoryStream(Encoding.UTF8.GetBytes(configuration.PrivateKey)); var connectionInfo = new ConnectionInfo(configuration.Host, configuration.Port, configuration.User, new PrivateKeyAuthenticationMethod(configuration.User, new PrivateKeyFile(keyStream))); _sshClient = new Renci.SshNet.SshClient(connectionInfo); _sshClient.Connect(); }
public void connect() { try { if (_client.IsConnected == false) { _client.Connect(); } } catch (Exception ex) { throw new Exception("Cannot connect to the host. " + ex.Message, ex); } }
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>") }; } }
private void btn_C1_Click(object sender, EventArgs e) { sshC = new SshClient(txt_ip1.Text, txt_user1.Text, txt_pwd1.Text); sshC.Connect(); if (sshC.IsConnected) { lab_ContentState1.Text = "连接状态:成功"; } else { lab_ContentState1.Text = "连接状态:失败"; } }
//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 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 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(); } }
public Client(string host, string username, string password) { this.Host = host; this.UserName = username; this.Password = password; //sshClient.ConnectionInfo.Username = "******"; sshClient.Connect(); ShowResponse = true; evt.Reset(); shell = new SshShell(this.Host, this.UserName, this.Password); thr = new Thread(Read); }
private void InternalConnect(string host, int port, string username, string password, string workingDirectory) { if (_isConnected) { // Change the working directory only if we use ScpClient. if (_scpClient != null) { ChangeWorkingDirectory(workingDirectory); } return; } // Restart timer _stopWatch.Restart(); _lastElapsedMilliseconds = 0; // Start connection ... PrintTime($"Connecting to {username}@{host}:{port} ..."); _sshClient = new SshClient(host, port, username, password); _sshClient.Connect(); try { // Use SFTP for file transfers var sftpClient = new SftpClient(host, port, username, password); sftpClient.Connect(); _sftpClient = sftpClient; } catch (Exception ex) { // Use SCP if SFTP fails PrintTime($"Error: {ex.Message} Is SFTP supported for {username}@{host}:{port}? We are using SCP instead!"); _scpClient = new ScpClient(host, port, username, password); _scpClient.Connect(); } var _connectionInfo = _sshClient.ConnectionInfo; PrintTime($"Connected to {_connectionInfo.Username}@{_connectionInfo.Host}:{_connectionInfo.Port} via SSH and {(_sftpClient != null ? "SFTP" : "SCP")}"); _isConnected = true; ChangeWorkingDirectory(workingDirectory); }
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); }
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(); // } } }
private void btn_Q2_Click(object sender, EventArgs e) { sshC = new SshClient("192.168.10.131", "root", "123123"); sshC.KeepAliveInterval = new TimeSpan(0, 0, 30); sshC.ConnectionInfo.Timeout = new TimeSpan(0, 0, 20); sshC.Connect(); // 动态链接 ForwardedPortDynamic port = new ForwardedPortDynamic("127.0.0.1", 22); sshC.AddForwardedPort(port); port.Start(); ////var fport = new ForwardedPortRemote("192.168.10.131", 22, "127.0.0.1", 22); ////sshC.AddForwardedPort(fport); ////fport.Start(); ////string x = sshC.RunCommand("pwd").Result; ; string x = sshC.RunCommand("pwd").Result; ; }
private void btn_C2_Click(object sender, EventArgs e) { /* * Resources.HOST 192.168.10.131 * Resources.PORT 22 * Resources.USERNAME root * proxyHost * Resources.PORT * Resources.USERNAME * Resources.PASSWORD * Resources.USERNAME */ var connectionInfo = new ConnectionInfo("10.69.66.67", 22, "toor4nsn", ProxyTypes.None, "192.168.253.18", 22, "toor4nsn", "oZPS0POrRieRtu", new KeyboardInteractiveAuthenticationMethod("10.69.66.67")); Renci.SshNet.SshClient _session2 = new Renci.SshNet.SshClient(connectionInfo); _session2.Connect(); _session2.RunCommand("lst"); //Renci.SshNet.Session zz = new Renci.SshNet.Session(,); //xx.Start(); }
/// <summary> /// Connects client to the server. /// </summary> public void Connect() { _sshClient.Connect(); }
public void sshConnect() { ssh = new SshClient(connectionInfo); ssh.Connect(); }
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 SSHConnection(string host, string username) { this._host = host; this._username = username; _ssh = new SshClient(_host, _username, Passwords.FetchPassword(_host, _username)); _ssh.Connect(); _stream = _ssh.CreateShellStream("commands", 240, 200, 132, 80, 240 * 200); // Next job, wait until we get a command prompt _stream.WriteLine("# this is a test"); DumpTillFind(_stream, "# this is a test"); _prompt = _stream.ReadLine(); }
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(); }