//Save the file Script.txt public static String SaveGenScriptSSH(string fileName) { StringBuilder sb = new StringBuilder(); SshStream ssh = null; String RouterIP = System.Web.Configuration.WebConfigurationManager.AppSettings.Get("RouterIP"); String RouterUser = System.Web.Configuration.WebConfigurationManager.AppSettings.Get("RouterUser"); String RouterPass = System.Web.Configuration.WebConfigurationManager.AppSettings.Get("RouterPass"); ssh = new SshStream(RouterIP, RouterUser, RouterPass); if (File.Exists(fileName)) { // Open the file to read from. string[] readText = File.ReadAllLines(fileName); foreach (string str in readText) { ssh.Write(str); System.Threading.Thread.Sleep(200); sb.AppendLine(ssh.ReadResponse()); } } else { throw new System.ArgumentException("File with script to send via SSH found"); } System.Threading.Thread.Sleep(500); ssh.Close(); return sb.ToString(); }
public void SSH_Connect(string IP) { this.ssh_rx = new SshStream(IP, "root", "fiskopter348"); this.ssh_rx.Write("stty -F /dev/ttyUSB0 sane raw -echo -echoe -echok 115200"); this.ssh_rx.Write("echo \"PC_Connected_to_Fiscopter\n\" > /dev/ttyUSB0"); this.ssh_rx.Write("cat /dev/ttyUSB0"); MessageBox.Show(this.ssh_rx.ReadResponse()); this.ssh_rx.BeginRead(rx_buff, 0, rx_buff.Length, rx_clbk, new object()); }
public static void MakeNewDirectory(string dirName) { //create a new ssh stream using (SshStream ssh = new SshStream(MACHINE_IP, USER_NAME, PASSWORD)) { //writing to the ssh channel ssh.Write("mkdir " + dirName); } }
/// <summary> /// 打开连接 /// </summary> /// <param name="host"></param> /// <param name="username"></param> /// <param name="pwd"></param> /// <param name="privateKeyPath"></param> /// <returns></returns> public bool OpenShell(string host, string username, string pwd, string privateKeyPath) { try { ////Redirect standard I/O to the SSH channel inputstream = new SshStream(host, username, pwd, privateKeyPath); ///我手动加进去的方法。。为了读取输出信息 inputstream.set_OutputStream(outputstream); return(inputstream != null); } catch { throw; } }
private string GenerateSizeFile() { SshStream ssh = new SshStream(txtHostForCleanup.Text, "autoengine", ""); //Set the end of response matcher character string response = string.Empty; try { ssh.Prompt = "\\$"; //Remove terminal emulation characters ssh.RemoveTerminalEmulationCharacters = true; //Writing to the SSH channel //tmReturn.Start(); //Remove terminal emulation characters ssh.RemoveTerminalEmulationCharacters = true; //Writing to the SSH channel ssh.Write("cd " + txtInputEnvForCleanup.Text); //Reading from the SSH channel response = ssh.ReadResponse(); //file * | grep directory | egrep -v "exclusion|list" | cut -d":" -f1 | xargs rm-Rf ssh.Write("du -sh > size.log"); response = ssh.ReadResponse(); ssh.Write("du -sh > size.log"); response = ssh.ReadResponse(); Console.WriteLine(response); return "Env Size: "+response; } catch (Exception ex) { CommonUtils.LogError(ex.Message, ex); } return string.Empty; }
private void StartComparison(string inputEnv, string inputHost, string refEnv, string refHost, string compareScriptLocation, out DataTable resultsTable) { resultsTable = new DataTable(); string scriptHost = "dell014srv"; bgDoServerWork.ReportProgress(5, "Validating environments..."); if (LOCAL_TA_USAGE || IsValidToBeginDiff(inputEnv, inputHost, refEnv, refHost, compareScriptLocation, scriptHost)) { bgDoServerWork.ReportProgress(5, "Connecting to Hosts..."); if (bgDoServerWork.CancellationPending) { WorkerWasCancelled = true; return; } //CopyComparisonScript(refHost, refEnv); SshStream ssh = new SshStream(scriptHost, "autoengine", ""); //Set the end of response matcher character string response = string.Empty; try { ssh.Prompt = "\\$"; //Remove terminal emulation characters ssh.RemoveTerminalEmulationCharacters = true; //Writing to the SSH channel //tmReturn.Start(); //Remove terminal emulation characters ssh.RemoveTerminalEmulationCharacters = true; //Writing to the SSH channel ssh.Write("cd " + compareScriptLocation); //Reading from the SSH channel response = ssh.ReadResponse(); } catch (Exception ex) { CommonUtils.LogError(ex.Message, ex); } string comparisonFolderName = DateTime.Now.Ticks.ToString(); string comparisonFileName = comparisonFolderName + "comparison.log"; if (bgDoServerWork.CancellationPending) { WorkerWasCancelled = true; return; } try { ssh.Write("mkdir " + comparisonFolderName); response = ssh.ReadResponse(); ssh.Write("cp comparison88.sh " + comparisonFolderName); response = ssh.ReadResponse(); ssh.Write("cd " + comparisonFolderName); //Reading from the SSH channel response = ssh.ReadResponse(); ssh.Write("comparison88.sh " + "/net/" + refHost + refEnv + " /net/" + inputHost + inputEnv + " -A >" + comparisonFileName); bgDoServerWork.ReportProgress(5, "Starting Comparison..."); response = ssh.ReadResponse(); ssh.Write("d"); response = ssh.ReadResponse(); } catch (Exception ex) { CommonUtils.LogError(ex.Message, ex); } bgDoServerWork.ReportProgress(5, "Comparison Completed"); if (bgDoServerWork.CancellationPending) { WorkerWasCancelled = true; return; } FtpConnection connection = new FtpConnection(scriptHost, "mxftp", "mxftp"); string localFileName = Path.GetTempFileName(); try { try { try { connection.Open(); bgDoServerWork.ReportProgress(5, "Validating Results..."); } catch (Exception ex) { CommonUtils.ShowError(ex.Message, ex); } connection.Login(); connection.SetCurrentDirectory(compareScriptLocation + comparisonFolderName); //Path.GetTempFileName connection.GetFile(comparisonFileName, localFileName, false); connection.RemoveFile(comparisonFileName); connection.SetCurrentDirectory(compareScriptLocation); bgDoServerWork.ReportProgress(5, "Building Output..."); } finally { connection.Close(); connection.Dispose(); } } catch (Exception ex) { CommonUtils.LogError(ex.Message, ex); } try { ssh.Write("cd .."); //Reading from the SSH channel response = ssh.ReadResponse(); ssh.Write("rm -rf " + comparisonFolderName); //Reading from the SSH channel response = ssh.ReadResponse(); ssh.Flush(); ssh.Close(); ssh.Dispose(); if (bgDoServerWork.CancellationPending) { WorkerWasCancelled = true; return; } } catch (Exception ex) { CommonUtils.LogError(ex.Message, ex); } try { string readFile = CommonUtils.ReadFile(localFileName); // Regex regex = new Regex("-.*-"); string[] array = new string[1]; // array[0]= regex.Match(readFile).Value; array[0] = "\n\n"; string[] splitFile = readFile.Split(array, StringSplitOptions.RemoveEmptyEntries); int counter = 1; bgDoServerWork.ReportProgress(5, "Displaying Results..."); Regex diffRegex = new Regex("diff.*"); DataTable results = new DataTable(); results.Columns.Add("Number"); results.Columns.Add("Operation"); results.Columns.Add("FileSize"); results.Columns.Add("FileModifyDate"); results.Columns.Add("FileType"); results.Columns.Add("FileName"); List<string> monthAbbreviations = new List<string>() { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; for (int j = 2; j < splitFile.Length; j++) { string[] splitByLines = splitFile[j].Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); for (int k = 3; k < splitByLines.Length; k++) { //-rw-rw-r-- 1 autoengine murex 1201 Jul 10 16:58 test.txt //-rwxrwxr-x 1 autoengine murex 546 May 10 2008 script.sh* // "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", and "Dec" if (j == 2) { string fileName = splitByLines[k].Replace("/net/" + refHost + refEnv, "").Replace("/net/" + inputHost + inputEnv, ""); string[] splitFileName = fileName.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (diffRegex.Matches(fileName).Count == 0) { DateTime date; try { if (splitFileName[7].Contains(":")) { date = new DateTime(DateTime.Now.Year, monthAbbreviations.IndexOf(splitFileName[5]), Convert.ToInt32(splitFileName[6]), Convert.ToInt32(splitFileName[7].Split(new char[] { ':' })[0]), Convert.ToInt32(splitFileName[7].Split(new char[] { ':' })[1]), 0); } else { date = new DateTime(Convert.ToInt32(splitFileName[7]), monthAbbreviations.IndexOf(splitFileName[5]), Convert.ToInt32(splitFileName[6])); } } catch (Exception ex) { CommonUtils.LogError("Could not get Date", ex); date = DateTime.Now; } long fileSize = (Convert.ToInt64(splitFileName[4]) / 1024) == 0 ? 1 : (Convert.ToInt64(splitFileName[4]) / 1024); results.Rows.Add(new object[] { counter, "Added", fileSize, date.ToString(), GetFileTypeFromExtension(splitFileName[8]), splitFileName[8] }); } } else { string fileName = splitByLines[k].Replace("/net/" + refHost + refEnv, "").Replace("/net/" + inputHost + inputEnv, ""); string[] splitFileName = fileName.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (diffRegex.Matches(fileName).Count == 0) { DateTime date; try { if (splitFileName[7].Contains(":")) { date = new DateTime(DateTime.Now.Year, monthAbbreviations.IndexOf(splitFileName[5]), Convert.ToInt32(splitFileName[6]), Convert.ToInt32(splitFileName[7].Split(new char[] { ':' })[0]), Convert.ToInt32(splitFileName[7].Split(new char[] { ':' })[1]), 0); } else { date = new DateTime(Convert.ToInt32(splitFileName[7]), monthAbbreviations.IndexOf(splitFileName[5]), Convert.ToInt32(splitFileName[6])); } } catch (Exception ex) { CommonUtils.LogError("Could not get Date", ex); date = DateTime.Now; } long fileSize = (Convert.ToInt64(splitFileName[4]) / 1024) == 0 ? 1 : (Convert.ToInt64(splitFileName[4]) / 1024); results.Rows.Add(new object[] { counter, "Modified", fileSize, date.ToString(), GetFileTypeFromExtension(splitFileName[8]), splitFileName[8] }); } } counter++; } } SAVED_SEARCH_RESULTS = results.Copy(); GOLDEN_ORIGINAL_RESTULS = results.Copy(); resultsTable = SAVED_SEARCH_RESULTS; } catch (Exception ex) { CommonUtils.LogError(ex.Message, ex); } } else { bgDoServerWork.CancelAsync(); WorkerWasCancelled = true; } }
private void RunScriptsOnServer(List<EnvComparisonFilter> selectedFilters) { string scriptToRunWithExclusion = "find . -name \"#pattern#\" | egrep -v \"#exclusionList#\" | cut -d\":\" -f1 | xargs rm "; string scriptToRunWithoutExclusion = "find . -name \"#pattern#\" | cut -d\":\" -f1 | xargs rm "; //CopyComparisonScript(refHost, refEnv); SshStream ssh = new SshStream(txtHostForCleanup.Text, "autoengine", ""); //Set the end of response matcher character string response = string.Empty; try { ssh.Prompt = "\\$"; //Remove terminal emulation characters ssh.RemoveTerminalEmulationCharacters = true; //Writing to the SSH channel //tmReturn.Start(); //Remove terminal emulation characters ssh.RemoveTerminalEmulationCharacters = true; //Writing to the SSH channel ssh.Write("cd " + txtInputEnvForCleanup.Text); //Reading from the SSH channel response = ssh.ReadResponse(); //file * | grep directory | egrep -v "exclusion|list" | cut -d":" -f1 | xargs rm-Rf foreach (EnvComparisonFilter cleanupFilter in selectedFilters) { string script = string.Empty; if (string.IsNullOrEmpty(cleanupFilter.ExclusionList)) { script = scriptToRunWithoutExclusion.Replace("#pattern#",cleanupFilter.FilterPattern) + (cleanupFilter.IsFolderDeletion ? "" : "-Rf"); } else { script = scriptToRunWithExclusion.Replace("#pattern#",cleanupFilter.FilterPattern).Replace("#exclusionList#", cleanupFilter.ExclusionList.Replace(",","|")) + (cleanupFilter.IsFolderDeletion ? "" : "-Rf"); } ssh.Write(script); response = ssh.ReadResponse(); Console.WriteLine(response); } ssh.Write("du -sh > sizeafter.log"); GetSizeAfterCleanup("sizeafter.log"); } catch (Exception ex) { CommonUtils.LogError(ex.Message, ex); } }
//System.Random randomNumbeGenerator = new System.Random(); private SshStream getShell() { SshStream ssh = new SshStream(HostName, UserName, Password); ssh.Prompt = "#"; ssh.RemoveTerminalEmulationCharacters = true; return ssh; }
public void ssh_command(string type, string host, string user, string password, string command) { if (type == "list dir") { Sftp sftp = new Sftp(host, user, password); try { sftp.Connect(); ArrayList analyses = sftp.GetFileList(command); if (analyses.Count > 0) { foreach (string run in analyses) { if (run.Length > 10) { this.stdRunsList.Items.Add(run); } } count_label.Text = "Count: " + stdRunsList.Items.Count.ToString(); connected(); } } catch { ConnectionError.Visible = true; pwdBox.ResetText(); } finally { sftp.Close(); } } else if (type == "kill") { ssh.Write(command); terminalThread.CancelAsync(); } else { try { ssh = new SshStream(host, user, password); abort = false; stopWatch.Start(); terminalThread.RunWorkerAsync(); checkThread.RunWorkerAsync(); ssh.Write(command); } catch (Exception ex) { MessageBox.Show(ex.Message, "Minion - Stream Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
private bool ConnectSSH() { try { SSHConnection = new SshStream(tbxIPAddress.Text, "pi", "raspberry"); isSSHConnected = true; return true; } catch (Exception exc) { MessageBox.Show(exc.Message); } isSSHConnected = false; return false; }
private void btnTest_Click(object sender, EventArgs e) { try { ssh = new SshStream("dell036srv", "autoengine", ""); //Set the end of response matcher character ssh.Prompt = "\\$"; //Remove terminal emulation characters ssh.RemoveTerminalEmulationCharacters = true; //Writing to the SSH channel ssh.Write("cd /dell036srv3/apps/qa27144_TPK0001018_6297137"); //Reading from the SSH channel string response = ssh.ReadResponse(); ssh.Write("ll -ltr *all*"); //Reading from the SSH channel response = ssh.ReadResponse(); } catch (Exception ex) { FrontendUtils.ShowError(ex.Message, ex); } }
private void btnInit_Click(object sender, EventArgs e) { try { ssh = new SshStream(txtHost.Text, "autoengine", ""); //Set the end of response matcher character ssh.Prompt = "\\$"; //Remove terminal emulation characters ssh.RemoveTerminalEmulationCharacters = true; //Writing to the SSH channel //tmReturn.Start(); } catch (Exception ex) { FrontendUtils.ShowError(ex.Message, ex); } }
private void InitializeSSh() { ssh = new SshStream("dell014srv", "autoengine", ""); //Set the end of response matcher character ssh.Prompt = "\\$"; //Remove terminal emulation characters ssh.RemoveTerminalEmulationCharacters = true; //Writing to the SSH channel //tmReturn.Start();; }
private void RebButton_Click(object sender, EventArgs e) { DialogResult Result = MessageBox.Show("Are you sure you wish to reboot?", "Warning", MessageBoxButtons.YesNo); if (Result == DialogResult.Yes) { host = DefaultIP.Text; SshStream ssh = new SshStream(host, user, pass); string command = "reboot"; ssh.Write(command); } }
/// <summary> /// This class creates a new SSH stream. /// </summary> /// <param name="host">The host to connect to.</param> /// <param name="username">The user that will be using the stream.</param> /// <param name="password">The password that will allow the user to connect.</param> public void createSSHStream(string host, string username, string password) { stream = new SshStream(host, username, password); stream.Prompt = "[root@131-server ~]#"; MessageBox.Show("Prompt: " + stream.Prompt); }
protected Dictionary<string, COrderData> WebProcess_List_ = new Dictionary<string, COrderData>(); // 웹에서 사용처리 해야하는것 #endregion Fields #region Methods public Int32 BarCodeImageCreate(string PinCode, int OrderSeq) { try { Int32 Result = 0; string makefile = HKLibrary.UTIL.HKFileHelper.GetCurrentDirectory(); string sDirPath; sDirPath = makefile + "\\data"; DirectoryInfo di = new DirectoryInfo(sDirPath); if (di.Exists == false) { di.Create(); } makefile += "\\"; makefile += "data"; makefile += "\\"; makefile += PinCode; makefile += ".jpg"; string folderName = Convert.ToString(OrderSeq); string ftpfileName = folderName + "/" + PinCode + ".jpg"; string ftpBasicPath = "/var/www/IMAGE/Web/upload/order/barcode/"; BarcodeLib.Barcode b = new BarcodeLib.Barcode(); b.Encode(BarcodeLib.TYPE.CODE128, PinCode); b.SaveImage(makefile, BarcodeLib.SaveTypes.JPG); //string ftpUri = "" + ftpBasicPath + folderName; SshStream ssh = new SshStream("ftp://ledev.leisureq.co.kr:10004/", "lion", "gkffl1!"); string ftpUri = "ftp://121.78.127.40:21/" + ftpBasicPath + folderName; FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUri); request.Method = WebRequestMethods.Ftp.MakeDirectory; //request.Method = WebRequestMethods.Ftp.UploadFile; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential("infobay", "info9887"); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); ftpUri = "ftp://121.78.127.40:21/" + ftpBasicPath + ftpfileName; request = (FtpWebRequest)WebRequest.Create(ftpUri); request.Method = WebRequestMethods.Ftp.UploadFile; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential("infobay", "info9887"); byte[] fileContents = File.ReadAllBytes(makefile); request.ContentLength = fileContents.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close(); response = (FtpWebResponse)request.GetResponse(); response.Close(); return Result; } catch (System.Exception ex) { return 0; } }
public string Connect(string host, string username, string password) { _sshStream = new SshStream(host, username, password) { RemoveTerminalEmulationCharacters = true, Prompt = @"\[[^@]*@[^]]*]\s>\s?$" }; return _sshStream.ReadResponse(); }
public void SSH_Connect(string IP) { this.ssh_tx = new SshStream(IP, "root", "fiskopter348"); this.ssh_tx.Write("stty -F /dev/ttyUSB0 sane raw -echo -echoe -echok 115200"); }