private string ExecuteSSH(string _command, SshShell _shell) { _shell.WriteLine(_command); string strReturn = _shell.Expect("#"); return(strReturn + "<br/>"); }
public static void RunExample() { try { SshConnectionInfo input = Util.GetInput(); SshShell shell = new SshShell(input.Host, input.User); if (input.Pass != null) { shell.Password = input.Pass; } if (input.IdentityFile != null) { shell.AddIdentityFile(input.IdentityFile); } //This statement must be prior to connecting shell.RedirectToConsole(); Console.Write("Connecting..."); shell.Connect(); Console.WriteLine("OK"); while (shell.ShellOpened) { System.Threading.Thread.Sleep(500); } Console.Write("Disconnecting..."); shell.Close(); Console.WriteLine("OK"); } catch (Exception e) { Console.WriteLine(e.Message); } }
protected override void BeginProcessing() { SshShell sshShell = null; switch (this.ParameterSetName) { case "PasswordAuthentication": sshShell = new SshShell(this.SshHost, this.User, this.Port); sshShell.SetPasswordAuthentication(this.Password); break; case "PrivateKeyAuthentication": sshShell = new SshShell(this.SshHost, this.User, this.Port); sshShell.SetPrivateKeyAuthentication(this.PrivateKeyFile, this.Passphrase); break; case "CredentialAuthentication": sshShell = new SshShell(this.SshHost, this.Credential.UserName, this.Port); sshShell.SetPasswordAuthentication(this.Credential.GetNetworkCredential().Password); break; } sshShell.ConnectionTimeout = this.ConnectionTimeout; sshShell.Connect(); this.WriteObject(sshShell); }
public bool Connect() { bool _result = false; try { if (m_Shell != null) { try { m_Shell.Close(); } catch { } } m_Shell = new SshShell(FileManager.Configuration.Options.SSHOptions.SSHHost, FileManager.Configuration.Options.SSHOptions.SSHUser, FileManager.Configuration.Options.SSHOptions.SSHPass); int _port = 22; try { _port = Int32.Parse(FileManager.Configuration.Options.SSHOptions.SSHPort); } catch { } m_Shell.Connect(_port); _result = m_Shell.Connected; } catch (Exception ex) { Loggy.Logger.DebugException("SSH Connect: ", ex); } return(_result); }
public void Test_Vagrant_Connect() { SshConnectionInfo input = UserInput; SshShell shell = new SshShell(input.Host, input.User); if (input.Pass != null) { shell.Password = input.Pass; } if (input.IdentityFile != null) { shell.AddIdentityFile(input.IdentityFile); } //This statement must be prior to connecting shell.RedirectToConsole(); Console.Write("Connecting..."); shell.Connect(); Console.WriteLine("OK"); // SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2 Console.WriteLine("server=" + shell.ServerVersion); SshExec shellExec = null; if (shell.ShellOpened) { // shell.Close(); shellExec = SshExec.Clone(shell); // new SshExec(shell.Host, shell.Username, shell.Password); shellExec.Connect(); } if (shellExec != null && shellExec.Connected) { var session = shellExec.Session; var channel = shellExec.Channel; Console.WriteLine(session); Console.WriteLine(channel); var stream = shellExec.RunCommandEx("ls -l", true); // = shell.StreamASCII(); while (stream.MoveNext()) { Console.WriteLine(stream.Current); } System.Threading.Thread.Sleep(500); } Console.Write("Disconnecting..."); if (shellExec != null) { shellExec.Close(); } Console.WriteLine("OK"); }
/// <summary> /// Open a Connection /// </summary> /// <param name="username"></param> /// <param name="password"></param> public override void OnOpenConnection(string username, SecureString password) { try { if (_sessionWindow == null) { throw new ProtocolException(beRemoteExInfoPackage.MajorInformationPackage, "SSH not initialized!"); } if (SessionWindow.IsSendInputRegistered == false) { SessionWindow.SendInput += SessionWindowSendInput; } //Load the configuration _sshTimeout = Convert.ToInt32(GetSessionSettings()["ssh.timeout"].GetProtocolSettingValue().GetValue()); try { //Create SSH Connection SshConnectionInfo input; input.Host = GetSessionServer().GetRemoteIP().ToString(); input.User = username; input.Pass = password == null ? null : Helper.ConvertToUnsecureString(password); //if (input.IdentityFile != null) shell.AddIdentityFile(input.IdentityFile); _sshConnection = new SshShell(input.Host, input.User); _readerStream = new MemoryStream(); if (input.Pass != null) { _sshConnection.Password = input.Pass; } //if (input.IdentityFile != null) shell.AddIdentityFile(input.IdentityFile); //This statement must be prior to connecting //_SshConnection.RedirectToConsole(); WriteDisplayText("Connecting..."); _sshConnection.Connect(); WriteDisplayText(_sshConnection.Expect()); } catch (Exception ea) { Logger.Log(LogEntryType.Warning, "Cannot connect to SSH-Server.", ea); WriteDisplayText(Environment.NewLine + "***Cannot connect to SSH-Server."); WriteDisplayText(Environment.NewLine + ea.Message); return; } WaitForSessionClose(); CloseConnection(); } catch (Exception ea) { Logger.Log(LogEntryType.Warning, "An unknown error occures on starting SSH-session", ea); } }
public string GetMacAddress(string _host, int _boot_groupid, int _environment, Log oLog, string _name, string _serial) { oLog.AddEvent(_name, _serial, "Starting MAC Address lookup...", LoggingType.Debug); string strMAC = ""; if (_boot_groupid > 0) { Models oModel = new Models(0, dsn); string strUsername = oModel.GetBootGroup(_boot_groupid, "username"); string strPassword = oModel.GetBootGroup(_boot_groupid, "password"); string strExpects = oModel.GetBootGroup(_boot_groupid, "regular"); string strCommand = oModel.GetBootGroup(_boot_groupid, "mac_query_command"); string strStart = oModel.GetBootGroup(_boot_groupid, "mac_query_substring_start"); oLog.AddEvent(_name, _serial, "Connecting...", LoggingType.Debug); SshShell oSSHshell = new SshShell(_host, strUsername, strPassword); oSSHshell.RemoveTerminalEmulationCharacters = true; oSSHshell.Connect(); string[] strExpect = strExpects.Split(new char[] { '|' }); if (oSSHshell.Connected == true && oSSHshell.ShellOpened == true) { // Wait for prompt string strBanner = oSSHshell.Expect(strExpects); oLog.AddEvent(_name, _serial, "Received banner prompt = " + strBanner, LoggingType.Debug); if (IsInOutput(strBanner, strExpect) == false) { oLog.AddEvent(_name, _serial, "Did not recieve all the output...trying again # 1...", LoggingType.Debug); strBanner = oSSHshell.Expect(strExpects); oLog.AddEvent(_name, _serial, "Received banner prompt # 1 = " + strBanner, LoggingType.Debug); } if (IsInOutput(strBanner, strExpect) == false) { oLog.AddEvent(_name, _serial, "Did not recieve all the output...trying again # 2...", LoggingType.Debug); strBanner = oSSHshell.Expect(strExpects); oLog.AddEvent(_name, _serial, "Received banner prompt # 2 = " + strBanner, LoggingType.Debug); } if (IsInOutput(strBanner, strExpect) == false) { oLog.AddEvent(_name, _serial, "Did not recieve all the output...trying again # 3...", LoggingType.Debug); strBanner = oSSHshell.Expect(strExpects); oLog.AddEvent(_name, _serial, "Received banner prompt # 3 = " + strBanner, LoggingType.Debug); } if (IsInOutput(strBanner, strExpect) == true) { oLog.AddEvent(_name, _serial, "Writing command = " + strCommand, LoggingType.Debug); // Send Command to get MAC Address oSSHshell.WriteLine(strCommand); // Wait for prompt strMAC = oSSHshell.Expect(strExpects); oLog.AddEvent(_name, _serial, "Received Response = " + strMAC, LoggingType.Debug); oLog.AddEvent(_name, _serial, "Parsing using " + strStart, LoggingType.Debug); strMAC = ParseOutput(strMAC, strStart, Environment.NewLine); } } oSSHshell.Close(); } return(strMAC); }
//public void smb_enumusers(string mytarget) public List <string> smb_enumusers(string mytarget) { List <string> SMBusers = new List <string>(); SshShell sshShell = connect(); string stdout = ""; //string stderr = ""; string cmd1 = "cd /home/root/tools/metasploitsvn"; //Hardcoded prompt1 = prompt + "/home/root/tools/metasploitsvn" + promptend; //sshShell.WriteLine(cmd1); //stdout = sshShell.Expect(prompt1); cmd1 = "./msfcli auxiliary/scanner/smb/smb_enumusers RHOSTS=" + mytarget + " E"; //Hardcoded sshShell.WriteLine(cmd1); stdout = sshShell.Expect(prompt1); Console.WriteLine(stdout); /* * RHOSTS => 111.222.333.444 * [*] 111.222.333.444 xmachine [ nobody, nxpgsql ] ( LockoutTries=0 PasswordMin=5 * ) * [*] Scanned 1 of 1 hosts (100% complete) * [*] Auxiliary module execution completed */ Regex myRegex = new Regex(Regex.Escape("[") + "[^<>]*" + Regex.Escape("]")); string[] mytab = Regex.Split(stdout, "\r\n"); foreach (string line in mytab) { if (line.Contains(mytarget)) { string strTemp = myRegex.Match(line.Replace("[*]", "")).ToString(); if (strTemp != "") { //Console.WriteLine("users:" + strTemp); //[ nobody, nxpgsql ] strTemp = strTemp.Replace("[", ""); strTemp = strTemp.Replace("]", "").Trim(); string[] myusers = Regex.Split(strTemp, ","); foreach (string user in myusers) { Console.WriteLine(user.Trim()); SMBusers.Add(user.Trim()); } } } } sshShell.Close(); return(SMBusers); }
private void ConfigureNexus() { try { Ping oPing = new Ping(); string strPingStatus = ""; try { PingReply oReply = oPing.Send(strSwitch); strPingStatus = oReply.Status.ToString().ToUpper(); } catch { } if (strPingStatus == "SUCCESS") { // Switch the port of strSwitchA, strInterfaceA oSSHshell = new SshShell(strSwitch, oVariable.NexusUsername(), oVariable.NexusPassword()); oSSHshell.RemoveTerminalEmulationCharacters = true; oSSHshell.Connect(); string strLogin = oAsset.GetDellSwitchportOutput(oSSHshell); if (strLogin != "**INVALID**") { oLog.AddEvent(intAnswer, strName, strSerial, "Successfully logged into Switch (" + strSwitch + ")...Setting " + (oMode == DellBladeSwitchportMode.Trunk ? "TRUNK" : "ACCESS") + " Switchport (" + strInterface + ") to " + strVlan + " (override = " + (boolOverride ? "true" : "false") + ")", LoggingType.Information); string strResult = oAsset.ChangeDellSwitchport(oSSHshell, strInterface, oMode, strVlan, strNative, strDescription, boolOverride, intAsset); if (strResult == "") { oLog.AddEvent(intAnswer, strName, strSerial, "Successfully changed switchport " + strInterface + " on " + strSwitch, LoggingType.Information); Complete = true; // Done Configuring Switchports } else { Error = "There was a problem configuring the Dell Blade Switchport ~ Switch: " + strSwitch + ", Interface: " + strInterface + ", Error: " + strResult; oLog.AddEvent(intAnswer, strName, strSerial, Error, LoggingType.Error); } if (oSSHshell.ShellConnected == true && oSSHshell.ShellOpened == true) { oSSHshell.Close(); } } else { Error = "There was a problem logging into the Dell Blade Switch ~ Switch: " + strSwitch; oLog.AddEvent(intAnswer, strName, strSerial, Error, LoggingType.Error); } } else { Error = "There was a problem pinging the Dell Blade Switch ~ Switch: " + strSwitch + ", Status: " + strPingStatus; oLog.AddEvent(intAnswer, strName, strSerial, Error, LoggingType.Error); } } catch (Exception ex) { Error = "Physical Service (NexusThread - ConfigureNexus): " + "(Error Message: " + ex.Message + ") (Source: " + ex.Source + ") (Stack Trace: " + ex.StackTrace + ") [" + System.Environment.UserName + "]"; } }
public CaseProtocolExecutionForSsh(myConnectForSsh yourConnectInfo) { isConnect = false; myExecutionDeviceInfo = yourConnectInfo; sshShell = new SshShell(myExecutionDeviceInfo.host, myExecutionDeviceInfo.user, myExecutionDeviceInfo.password); if (myExecutionDeviceInfo.expectPattern != null) { sshShell.ExpectPattern = myExecutionDeviceInfo.expectPattern; } }
public static void RunExample() { try { SshConnectionInfo input = Util.GetInput(); SshShell ssh = new SshShell(input.Host, input.User); if (input.Pass != null) { ssh.Password = input.Pass; } if (input.IdentityFile != null) { ssh.AddIdentityFile(input.IdentityFile); } Console.Write("Connecting..."); ssh.Connect(); Console.WriteLine("OK"); Console.Write("Enter a pattern to expect in response [e.g. '#', '$', C:\\\\.*>, etc...]: "); string pattern = Console.ReadLine(); ssh.ExpectPattern = pattern; ssh.RemoveTerminalEmulationCharacters = true; Console.WriteLine(); Console.WriteLine(ssh.Expect(pattern)); while (ssh.ShellOpened) { Console.WriteLine(); Console.Write("Enter some data to write ['Enter' to cancel]: "); string data = Console.ReadLine(); if (data == "") { break; } ssh.WriteLine(data); string output = ssh.Expect(pattern); Console.WriteLine(output); } Console.Write("Disconnecting..."); ssh.Close(); Console.WriteLine("OK"); } catch (Exception e) { Console.WriteLine(e.Message); } }
/// <summary> /// Close the current Connection /// </summary> public override void CloseConnection() { WriteDisplayText("Disconnecting..."); _sshConnection.Close(); WriteDisplayText("OK"); _sshConnection = null; // Triggering upper close connection event! TriggerCloseConnectionEvent(); CloseTab(); }
static void Main(string[] args) { SshShell lol = new SshShell("10.10.99.2", "admin"); lol.Password = "******"; lol.RedirectToConsole(); lol.Connect(); while (lol.ShellOpened) { System.Threading.Thread.Sleep(500); } lol.Close(); }
public void Begin() { datStart = DateTime.Now; arProcessing = new int[4] { 45, 47, 92, 124 }; // 92 = \, 124 = |, 47 = /, 45 = - strSSH = ""; oModel = new Models(0, dsn); oModelsProperties = new ModelsProperties(0, dsn); oServer = new Servers(0, dsn); oSetting = new Settings(0, dsn); oOnDemand = new OnDemand(0, dsn); oSolaris = new Solaris(0, dsn); oEventLog = new Log(0, dsn); oFunction = new Functions(0, dsn, intEnvironment); strTo = oFunction.GetGetEmailAlertsEmailIds("EMAILGRP_PROVISIONING_SUPPORT"); intModel = Int32.Parse(oServer.Get(intServer, "modelid")); if (intModel > 0) { strModel = oModelsProperties.Get(intModel, "name"); Int32.TryParse(oModelsProperties.Get(intModel, "modelid"), out intModelParent); if (intModelParent > 0) { Int32.TryParse(oModel.Get(intModelParent, "boot_groupid"), out intModelBootGroup); } } if (intModelBootGroup > 0) { string strUsername = oModel.GetBootGroup(intModelBootGroup, "username"); string strPassword = oModel.GetBootGroup(intModelBootGroup, "password"); strReturnToALOM = oModel.GetBootGroup(intModelBootGroup, "return_to_alom"); oEventLog.AddEvent(strName, strSerial, "Connecting to " + strILO + "... (U:" + strUsername + ", P:****)", LoggingType.Information); oSSHshell = new SshShell(strILO, strUsername, strPassword); oSSHshell.RemoveTerminalEmulationCharacters = true; oSSHshell.Connect(); oEventLog.AddEvent(strName, strSerial, "Connected to " + strILO + "...sending commands...", LoggingType.Information); ThreadStart oReadingDoneSSH = new ThreadStart(ReadingDoneSSH); Thread oJobReadingDoneSSH = new Thread(oReadingDoneSSH); oJobReadingDoneSSH.Start(); ReadingSSH(); } else { AddResult("The boot group of the model has not been configured ~ (ModelPropertyID = " + intModel.ToString() + ") (ModelID = " + intModelParent.ToString() + ") (ModelBootGroupID = " + intModelBootGroup.ToString() + ")"); } }
protected string WriteLine(SshShell _shell, string _line) { CombinedStream oStream = (CombinedStream)(_shell.GetStream()); string strReturn = ""; for (int ii = 0; ii < _line.Length; ii++) { //oStream.Write(_line[ii].ToString()); _shell.Write(_line[ii].ToString()); System.Threading.Thread.Sleep(200); // sleep for a split second int intRead = oStream.ReadByte(); strReturn += _shell.GetStream(); } return(strReturn); }
private string runStatusCommand(SshShell shell, SshExec exec, string command) { string stdout = ""; string stderr = ""; shell.Connect(); shell.RedirectToConsole(); exec.Connect(); int ret = exec.RunCommand(command, ref stdout, ref stderr); exec.Close(); shell.Close(); return(stdout); }
//TODO //https://isc.sans.edu/ipinfo.html?ip= static SshShell connect() { port = 22; address = "192.168.1.2"; //TODO Hardcoded username = "******"; password = "******"; SshShell sshShell; sshShell = new SshShell(address, username, password); sshShell.RemoveTerminalEmulationCharacters = true; //string prompt; //prompt = "root@backtrack:~#"; //exec.Connect(address); //exec.Login(username, password); try { sshShell.Connect(port); string stdout = sshShell.Expect(prompt); //Utils.Helper_Trace("XORCISM PROVIDER XINFO", "stdoutconnect: " + stdout); } catch (Exception ex) { Utils.Helper_Trace("XORCISM PROVIDER XINFO", "Error in sshconnect to " + address + " " + ex.Message + " " + ex.InnerException); } Console.WriteLine("connected"); string cmd1 = "cd /home/root/tools/metasploitsvn"; //TODO Hardcoded sshShell.WriteLine(cmd1); //prompt1 = prompt + "~/tools/metasploitsvn" + promptend; prompt1 = "/tools/metasploitsvn"; //HARDCODED sshShell.Expect(prompt1); //============================================== cmd1 = "svn update"; //Hardcoded sshShell.WriteLine(cmd1); Thread.Sleep(60000); sshShell.Expect(prompt1); return(sshShell); }
public void CheckJobStatus() { string stdout = ""; //string stderr = ""; bool atleastOne = false; SshShell shell = new SshShell(Consts.DEFAULT_HOST, Consts.DEFAULT_USERNAME, Consts.DEFAULT_PASSWORD); SshExec exec = new SshExec(Consts.DEFAULT_HOST, Consts.DEFAULT_USERNAME, Consts.DEFAULT_PASSWORD); Thread.Sleep(1000); string jobId; int runningJobs = 0; while (!atleastOne || runningJobs != 0) { stdout = runStatusCommand(shell, exec, "mapred job -list"); runningJobs = Int32.Parse(stdout.Split(null).ToList()[0]); if (runningJobs != 0) { atleastOne = true; jobId = stdout.Split(null).ToList().Where(line => line.Contains("job_")).First(); double map; double reduce; while (true) { stdout = runStatusCommand(shell, exec, $"mapred job -status {jobId}"); map = Double.Parse((stdout.Split('\n').Where(line => line.Contains("map()")).First().ToString()).Split(null)[2]) * 100; reduce = Double.Parse((stdout.Split('\n').Where(line => line.Contains("reduce()")).First().ToString()).Split(null)[2]) * 100; StatusModel.Instance.setProgress((int)((reduce + map) / 2), 100); StatusModel.Instance.Status = $"Map {(int)map}% - Reduce {(int)reduce}%"; if (reduce == 100) { break; } Thread.Sleep(500); } } } StatusModel.Instance.Status = "Finished MapReduce!"; }
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); }
public void search_email_collector(string domainname) { SshShell sshShell = connect(); string stdout = ""; //string stderr = ""; string cmd1 = "cd /home/root/tools/metasploitsvn"; //TODO Hardcoded prompt1 = prompt + "/home/root/tools/metasploitsvn" + promptend; sshShell.WriteLine(cmd1); stdout = sshShell.Expect(prompt1); cmd1 = "./msfcli auxiliary/gather/search_email_collector DOMAIN=" + domainname + " E"; //Hardcoded sshShell.WriteLine(cmd1); stdout = sshShell.Expect(prompt1); /* * DOMAIN => target.com * [*] Harvesting emails ..... * [*] Searching Google for email addresses from target.com * [*] Extracting emails from Google search results... * [*] Searching Bing email addresses from target.com * [*] Extracting emails from Bing search results... * [*] Searching Yahoo for email addresses from target.com * [*] Extracting emails from Yahoo search results... * [*] Located 2 email addresses for target.com * [*] [email protected] * [*] [email protected] * [*] Auxiliary module execution completed */ string[] mytab = Regex.Split(stdout, "\r\n"); foreach (string line in mytab) { if (line.Contains("@" + domainname)) { Console.WriteLine(line.Replace("[*]", "").Trim()); } } sshShell.Close(); }
static void Main(string[] args) { var serconfigPaht = AppDomain.CurrentDomain.BaseDirectory + "/config/server.config.json"; var configPath = AppDomain.CurrentDomain.BaseDirectory + "/config/dbCluster.config.cnf"; var configStr = File.ReadAllText(configPath); var serverConfigStr = File.ReadAllTextAsync(serconfigPaht).Result; var serverConfigJson = JObject.Parse(serverConfigStr); var taskList = new List <Task>(); foreach (var host in serverConfigJson["host"]) { var taskResult = Task.Run(() => { var shell = new SshShell(host.ToString(), "root", "Adminqwer!@#$"); shell.Connect(); foreach (var cmd in serverConfigJson["cmd"]) { var cmdTxt = cmd.ToString(); //Console.WriteLine(cmdTxt); switch (cmdTxt) { case "[writeConfig]": shell.WriteLine($"echo '{configStr}' > /var/lib/mysql-cluster/config.ini"); break; default: shell.WriteLine(cmdTxt); break; } //shell. } //shell.WriteLine("rm -rf ./*"); }); taskList.Add(taskResult); } Task.WaitAll(taskList.ToArray()); Console.Read(); }
static void Main(string[] args) { testScp(); try { string host = "192.168.0.3"; string user = "******"; string pass = "******"; Console.WriteLine("主机地址: {0}", host); Console.WriteLine("登陆用户: {0}", user); Console.WriteLine("登录密码: {0}", pass); SshShell shell = new SshShell(host, user); shell.Password = pass; shell.RedirectToConsole(); Console.Write("正在连接..."); shell.Connect(); Console.WriteLine("连接完毕!"); Console.WriteLine("========="); while (shell.ShellOpened) { System.Threading.Thread.Sleep(500); } Console.WriteLine("========="); Console.WriteLine("断开连接中..."); shell.Close(); Console.WriteLine("断开完毕"); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.Write("按任意键继续..."); Console.ReadKey(); Console.WriteLine("\b"); Environment.Exit(0); }
protected void Page_Load(object sender, EventArgs e) { string strUsername = "******"; string strPassword = "******"; //string strExpects = "sc>|[y/n]|} ok|return to ALOM"; string strExpects = "#"; SshShell oSSHshell = new SshShell("10.49.254.229", strUsername, strPassword); oSSHshell.RemoveTerminalEmulationCharacters = true; oSSHshell.Connect(); CombinedStream oSSHstream = (CombinedStream)(oSSHshell.GetStream()); if (oSSHshell.Connected == true && oSSHshell.ShellOpened == true) { //int bt = oSSHstream.ReadByte(); string strOutput = oSSHshell.Expect(strExpects); Response.Write(strOutput); } oSSHshell.Close(); }
public void Connect() { shell = new SshShell(user.Host, user.UserName, YSEncrypt.DecryptB(user.Password, KeysUtil.PassKey)); shell.Connect(user.Port); m_Channel = shell.getChannel(); session = shell.getSession(); sftpChannel = (ChannelSftp)session.openChannel("sftp"); sftpChannel.connect(); ThreadPool.QueueUserWorkItem((a) => { string line = null; while (RUN_CUT && shell.ShellOpened) { success = true; logger.Debug("Successed..."); sftpForm.HideTool(); System.Threading.Thread.Sleep(100); while ((line = m_Channel.GetMessage()) != null) { Console.WriteLine(line); } } logger.Debug("Disconnecting..."); Disconnection(); logger.Debug("OK"); }); dir = sftpChannel.getHome(); text_adress.Text = dir; LoadDirFilesToListView(dir); SetContentMenuItem(true); }
private void button1_Click(object sender, EventArgs e) { try { string host = tb_host.Text; string acc = tb_acc.Text; string pwd = tb_pwd.Text; shell = new SshShell(host, acc, pwd); //shell.RedirectToConsole(); shell.Connect(22); m_Channel = shell.getChannel(); string line = null; ThreadPool.QueueUserWorkItem((a) => { while (shell.ShellOpened) { System.Threading.Thread.Sleep(100); while ((line = m_Channel.GetMessage()) != null) { ShowLogger(line); } } Console.Write("Disconnecting..."); shell.Close(); Console.WriteLine("OK"); }); } catch (Exception ex) { Console.WriteLine(ex); } }
public void dns_enum(string domainname) { SshShell sshShell = connect(); string stdout = ""; //string stderr = ""; string cmd1 = "cd /home/root/tools/metasploitsvn"; //Hardcoded prompt1 = prompt + "/home/root/tools/metasploitsvn" + promptend; sshShell.WriteLine(cmd1); stdout = sshShell.Expect(prompt1); cmd1 = "./msfcli auxiliary/gather/dns_enum DOMAIN=" + domainname + " E"; //Hardcoded sshShell.WriteLine(cmd1); stdout = sshShell.Expect(prompt1); Console.Write(stdout); sshShell.Close(); }
public void vnc_login(string target) { SshShell sshShell = connect(); string stdout = ""; //string stderr = ""; string cmd1 = "cd /home/root/tools/metasploitsvn"; //Hardcoded prompt1 = prompt + "/home/root/tools/metasploitsvn" + promptend; sshShell.WriteLine(cmd1); stdout = sshShell.Expect(prompt1); cmd1 = "./msfcli auxiliary/scanner/vnc/vnc_login RHOSTS=" + target + " PASS_FILE=" + PASS_FILE + " STOP_ON_SUCCESS=true E"; //Hardcoded sshShell.WriteLine(cmd1); stdout = sshShell.Expect(prompt1); Console.Write(stdout); /* * [*] 8.6.6.8:5900 - Attempting VNC login with password 'computer' * [*] 8.6.6.8:5900, VNC server protocol version : 3.3 * [+] 8.6.6.8:5900, VNC server password : "******" * [*] Scanned 1 of 1 hosts (100% complete) * [*] Auxiliary module execution completed */ Regex myRegex = new Regex("VNC server password : "******"\"") + "[^<>]*" + Regex.Escape("\"")); string strTemp = myRegex.Match(stdout).ToString(); if (strTemp != "") { strTemp = strTemp.Replace("VNC server password : "******""); strTemp = strTemp.Replace("\"", ""); Console.Write(strTemp); } sshShell.Close(); }
static void Main(string[] args) { //SshConnectionInfo input = Util.GetInput(); SshShell shell = new SshShell("101.132.130.133", "root"); shell.Password = "******"; //This statement must be prior to connecting shell.RedirectToConsole(); Console.Write("Connecting..."); shell.Connect(); Console.WriteLine("OK"); while (shell.ShellOpened) { System.Threading.Thread.Sleep(500); } Console.Write("Disconnecting..."); shell.Close(); Console.WriteLine("OK"); Console.ReadKey(); }
//static void Main() static void blabla() { //int port; // string address, username, password; SshShell sshShell = connect(); string stdout = ""; //string stderr = ""; string cmd1 = "cd /home/root/tools/metasploitsvn"; //Hardcoded sshShell.WriteLine(cmd1); stdout = sshShell.Expect(prompt); //============================================== cmd1 = "svn update"; //Hardcoded sshShell.WriteLine(cmd1); stdout = sshShell.Expect(prompt); Utils.Helper_Trace("XORCISM PROVIDER METASPLOIT", string.Format("svn update = {0}", stdout)); }
public bool Parse() { Assembly a; /* A way for loading XMLfile */ a = Assembly.GetExecutingAssembly(); Utils.Helper_Trace("XORCISM PROVIDER NIKTO", "NIKTO Assembly location = " + a.Location); /* Name of XML result */ string file; file = string.Format("result_{0}_{1}.xml", DateTime.Now.Ticks, this.GetHashCode()); Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} Results will be stored in file [{1}]", m_jobId, file)); /* SSH instructions & declarations */ int port = 22; string address, username, password; string prompt; /* * address = "111.222.333.444"; * username = "******"; * password = "******"; * prompt = "root@xmachine:"; */ //HARDCODED address = "111.222.333.444"; username = "******"; password = "******"; prompt = "root"; //@backtrack: SshShell sshShell; sshShell = new SshShell(address, username, password); // sshShell.RemoveTerminalEmulationCharacters = true; Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} Connecting to NIKTO server at {1}", m_jobId, address)); try { sshShell.Connect(port); //sshShell.Expect(prompt+"~#"); sshShell.Expect(prompt);// + "~$"); } catch (Exception ex) { Utils.Helper_Trace("XORCISM PROVIDER NIKTO", "Error in sshconnection to " + address + " " + ex.Message + " " + ex.InnerException); } // if ssh connection if (sshShell.Connected) { Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} Successfully connected to NIKTO server", m_jobId)); //string output; string stdout = ""; /* Command 1 */ string cmd1; //cmd1 = "cd /home/tools/nikto-2.1.4"; cmd1 = "cd /home/root/tools/nikto-2.1.4"; //HARDCODED sshShell.WriteLine(cmd1); //prompt = prompt+"/home/tools/nikto-2.1.4#"; //prompt = "tools/nikto-2.1.4$"; stdout = sshShell.Expect(prompt); /* See for provider m_model */ /* For an URL */ /* * @ -T => tunning or strategy * @ -C all => to force check all possible dirs */ //cmd1 = string.Format("nikto -Format XML -o {2} -host {1} -T {3} -C all", m_policy, m_target, file, m_strategy); //-g -e 6 cmd1 = string.Format("./nikto.pl -Format XML -o {2} -host {1} -C all", m_policy, m_target, file); //-g -e 6 //HARDCODED Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} Executing command [{1}]", m_jobId, cmd1)); sshShell.WriteLine(cmd1); stdout = sshShell.Expect(prompt); Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} START DUMP STDOUT01", m_jobId)); Utils.Helper_Trace("XORCISM PROVIDER NIKTO", stdout); string localOutputFile; localOutputFile = Path.GetTempFileName(); Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("Downloading results via SFTP to [{0}]", localOutputFile)); nikto_get_result(file, localOutputFile); Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} XML PARSE successfull for file : [{1}] ", m_jobId, file)); //aff_list(); // Pause Console.ReadLine(); sshShell.Close(); sshShell = null; return(true); } else { Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} Connection failed to NIKTO server", m_jobId)); return(false); } }