/// <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; }
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 static String ExecuteCommand(SshClient sshClient, String command) { if (!sshClient.IsConnected) sshClient.Connect(); return sshClient.CreateCommand(command).Execute(); }
public SshCommand CreateSSHCommand(string userCommandText) { InternalConnect(_sshDeltaCopyOptions.Host, _sshDeltaCopyOptions.Port, _sshDeltaCopyOptions.Username, _sshDeltaCopyOptions.Password, _sshDeltaCopyOptions.DestinationDirectory); var commandText = $"cd \"{_sshDeltaCopyOptions.DestinationDirectory}\";{userCommandText}"; return(_sshClient.CreateCommand(commandText)); }
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); }
//выполнение команд с новым клиентом private void Execute(SshClient client, string command) { using (var cmd = client.CreateCommand(command)) { cmd.Execute(); _listResult.Add(cmd.Result); if (cmd.Error.Length != 0) { _listError.Add(cmd.Error); } } }
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 async Task Async(string commandText, string expected) { using var command = _sut.CreateCommand(commandText); command.CommandTimeout = TimeSpan.FromSeconds(5); var task = Task.Factory.FromAsync <string>( beginMethod: (callback, state) => command.BeginExecute(callback, state), endMethod: result => command.EndExecute(result), state: commandText); var actual = await task; Assert.NotNull(actual); Assert.NotEmpty(actual); Assert.Matches(expected, actual); }
public static string[] MakeRequest(SshClient client, string command) { SshCommand sshCommand = client.CreateCommand(command); var asynch = sshCommand.BeginExecute(); StreamReader streamReader = new StreamReader(sshCommand.OutputStream); string response = ""; while (!asynch.IsCompleted) { string result = streamReader.ReadToEnd(); if (result != "") { response += result; } } return response.TrimEnd('\r', '\n').Split('\n'); }
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");*/ }
/// <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 BeginService() { _client = new SshClient(Host, UserName, Password); _client.Connect(); _client.RunCommand("sudo pkill mono"); var call = string.Format("cd {0}", _homePiBuildindicatronServer); const string commandText = "sudo mono BuildIndicatron.Server.exe"; var text = call + " && " + commandText; _log.Info("Starting command:" + text); _runCommand = _client.CreateCommand(text); _beginExecute = _runCommand.BeginExecute(); streamReader = new StreamReader(_runCommand.OutputStream); WaitFor("Running", 6000).Wait(); }
/// <summary> /// Initializes a new instance of the <see cref="SshCommand"/> class. /// </summary> /// <param name="sshClient">The SSH client.</param> /// <param name="commandText">The command text.</param> /// <param name="encoding">The encoding to use for the results.</param> /// <exception cref="ArgumentNullException">Either <paramref name="commandText"/> is null.</exception> internal SshCommand(Renci.SshNet.SshClient sshClient, string commandText, Encoding encoding) { _sshCommand = sshClient.CreateCommand(commandText, encoding); }
public static void dir(string indir, string outdir) { string username = @"docker"; // Setup Credentials and Server Information string dockerHost = @"192.168.119.129"; ConnectionInfo ConnNfo = new ConnectionInfo(dockerHost, 22, username, new AuthenticationMethod[]{ // Password based Authentication new PasswordAuthenticationMethod(username, @"tcuser"), // Key Based Authentication (using keys in OpenSSH Format) //new PrivateKeyAuthenticationMethod(username,new PrivateKeyFile[]{ // new PrivateKeyFile(@"..\openssh.key","passphrase") //}), } ); //string dir = System.IO.Path.GetDirectoryName(outfile); // Execute a (SHELL) Command - prepare upload directory using (var sshclient = new SshClient(ConnNfo)) { sshclient.Connect(); // using (var cmd = sshclient.CreateCommand(@"ls /etc")) using (var cmd = sshclient.CreateCommand(@"mkdir -p " + outdir + @" && chmod +rw " + outdir)) { string output = cmd.Execute(); Console.WriteLine("Command>" + cmd.CommandText); Console.WriteLine(output); Console.WriteLine(cmd.Result); Console.WriteLine("Return Value = {0}", cmd.ExitStatus); } sshclient.Disconnect(); } // Upload A File using (var scp = new ScpClient(ConnNfo)) { scp.Connect(); scp.Upload(new System.IO.DirectoryInfo(indir), outdir); scp.Disconnect(); } }
private IEnumerable<statistics> GetDMI(SshClient client) { var cmdresult = client.CreateCommand("dmesg |grep DMI:").Execute().Split(new char[] { ':' }); if (cmdresult.Length == 2) { yield return new statistics() { type = StatisticsType.DMI.ToString(), val = cmdresult[1], }; } }
private string MikrotikExportCompact(string MikrotikIP, int MikrotikSSHPort, string MikrotikUser, string MikrotikPassword) { ConnectionInfo sLogin = new PasswordConnectionInfo(MikrotikIP, MikrotikSSHPort, MikrotikUser, MikrotikPassword); SshClient sClient = new SshClient(sLogin); sClient.Connect(); SshCommand appStatCmd = sClient.CreateCommand("export compact"); appStatCmd.Execute(); sClient.Disconnect(); sClient.Dispose(); return appStatCmd.Result; }
private IEnumerable<statistics> GetCPUCores(SshClient client) { var cmdresult = client.CreateCommand("cat /proc/cpuinfo | grep processor").Execute(); var lines = cmdresult.Split(new char[] { '\r', '\n' }).Where(l => l.Trim().Length > 0); yield return new statistics() { type = StatisticsType.CPUCores.ToString(), val = lines.Count().ToString(), }; }
private IEnumerable<statistics> GetUpSeconds(SshClient client) { var cmdresult = client.CreateCommand("cat /proc/uptime").Execute().Split(new char[] {' '}); double sec; if (double.TryParse(cmdresult[0], out sec)) { yield return new statistics() { type = StatisticsType.UpSeconds.ToString(), val = sec.ToString(), }; } }
private IEnumerable<statistics> GetMemInfo(SshClient client) { var cmdresult = client.CreateCommand("cat /proc/meminfo").Execute(); var lines = cmdresult.Split(new char[] { '\r', '\n' }); var infos = lines.Select(l => { var data = l.Split(new char[] { ':' }); if (data.Length == 2) return new Tuple<string, string>(data[0], data[1]); else return new Tuple<string, string>(data[0], string.Empty); }).ToDictionary(k => k.Item1); Func<string, double> convertToDouble = str => { if (str.EndsWith(" kB")) return Convert.ToDouble(str.Substring(0, str.Length - 3))*1000; else return 0; }; Tuple<string,string> d; if (infos.TryGetValue("MemTotal", out d)) yield return new statistics() { type = StatisticsType.MemInfoTotal.ToString(), val = convertToDouble(d.Item2).ToString(), }; if (infos.TryGetValue("MemFree", out d)) yield return new statistics() { type = StatisticsType.MemInfoFree.ToString(), val = convertToDouble(d.Item2).ToString(), }; }
private IEnumerable<statistics> GetMachineType(SshClient client) { var cmdresult = client.CreateCommand("uname -sr").Execute(); yield return new statistics() { type = StatisticsType.MachineType.ToString(), val = cmdresult, }; }
private IEnumerable<statistics> GetInterfaceIP(SshClient client) { var cmdresult = client.CreateCommand("ifconfig").Execute(); var lines = cmdresult.Split(new char[] { '\r', '\n' }); var regexlist = linuxregex; string currenteth = string.Empty; foreach (var l in lines) { if (l.Contains("Link encap:")) { currenteth = l.Split(' ').FirstOrDefault(); continue; } if (l.Contains(": flags=")) { currenteth = l.Split(':').FirstOrDefault(); regexlist = coreosregex; continue; } if (currenteth.Length == 0) continue; var foundmatch = regexlist.Select(r => Tuple.Create(r , r.regex.Match(l))).Where(r => r.Item2.Success).FirstOrDefault(); if (foundmatch == null) continue; foreach (var rd in foundmatch.Item1.regdata) { var val = foundmatch.Item2.Groups[rd.Item2].Value; if (rd.Item1 == StatisticsType.InterfaceIp) { if (val == "127.0.0.1") continue; } if (string.IsNullOrWhiteSpace(val)) continue; yield return new statistics() { type = rd.Item1.ToString(), val = val, category = currenteth, }; } } }
/// <summary> /// Runs a command on the specified PlanetLab node. /// </summary> /// <param name="state">The manager state.</param> /// <param name="node">The PlanetLab node state.</param> /// <param name="command">The PlanetLab command.</param> /// <param name="set">The command parameter set.</param> /// <param name="sshClient">The SSH client.</param> private void OnRunCommand(PlManagerState state, PlManagerNodeState node, PlCommand command, int set, SshClient sshClient) { // Raise the command started event. if (null != this.CommandStarted) this.CommandStarted(this, new PlManagerCommandEventArgs(state, node.Node, command, set)); try { // Compute the command text. string commandText = set >= 0 ? command.GetCommand(set) : command.Command; // The number of subcommands. int success = 0; int fail = 0; // Divide the command into subcommands. string[] subcommands = commandText.Split(PlManager.subcommandSeparators, StringSplitOptions.RemoveEmptyEntries); // For all subcommands. foreach (string subcommand in subcommands) { // If the operation has been paused, wait for resume. if (state.IsPaused) { state.WaitPause(); } // If the operation has been canceled, return. if (state.IsStopped) { // Raise the canceled event. if (null != this.CommandCanceled) this.CommandCanceled(this, new PlManagerCommandEventArgs(state, node.Node, command, set)); // Return. return; } // If the subcommand is empty, continue to the next subcommand. if (string.IsNullOrWhiteSpace(subcommand)) continue; // Create a new SSH command. using (SshCommand sshCommand = sshClient.CreateCommand(subcommand)) { try { // The command duration. TimeSpan duration; // The retry count. int retry = 0; do { // The start time. DateTime startTime = DateTime.Now; // Execute the command. sshCommand.Execute(); // Compute the command duration. duration = DateTime.Now - startTime; } while ((retry++ < state.Slice.CommandRetries) && (sshCommand.ExitStatus != 0)); // Create a new command state. PlManagerSubcommandState subcommandState = new PlManagerSubcommandState(node, sshCommand, duration, retry - 1); // Increment the number of successful subcommands. success++; // Add the subcommand. node.AddSubcommand(subcommandState); // Raise a subcommand success event. if (null != this.SubcommandSuccess) this.SubcommandSuccess(this, new PlManagerSubcommandEventArgs(state, node.Node, command, set, subcommandState)); } catch (Exception exception) { // Create a new subcommand state. PlManagerSubcommandState subcommandState = new PlManagerSubcommandState(node, sshCommand, exception); // Increment the number of failed subcommands. fail++; // Add the subcommand. node.AddSubcommand(subcommandState); // Raise a subcommand fail event. if (null != this.SubcommandFail) this.SubcommandFail(this, new PlManagerSubcommandEventArgs(state, node.Node, command, set, exception)); } } } // Raise a command completed event. if (null != this.CommandFinishedSuccess) this.CommandFinishedSuccess(this, new PlManagerCommandEventArgs(state, node.Node, command, set, success, fail)); } catch (Exception exception) { // Raise a command completed event. if (null != this.CommandFinishedFail) this.CommandFinishedFail(this, new PlManagerCommandEventArgs(state, node.Node, command, set, exception)); } }
private void RunCommand(SshClient sshClient, string command) { using (var sshCommand = sshClient.CreateCommand(command)) { sshCommand.Execute(); if (!string.IsNullOrEmpty(sshCommand.Result)) InstallationProgress.ProgressText += sshCommand.Result; if (!string.IsNullOrEmpty(sshCommand.Error) && sshCommand.ExitStatus != 0) throw new Exception(sshCommand.Error); } }
private IEnumerable<statistics> GetVolInfo(SshClient client) { var cmdresult = client.CreateCommand("df -P").Execute(); var lines = cmdresult.Split(new char[] { '\r', '\n' }); var infos = lines .Where(l => l.Trim().Length > 0) .Select(l => l.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)).Skip(1); foreach (var l in infos) { if (l[0].StartsWith("/dev") == false) continue; yield return new statistics() { type = StatisticsType.VolumeTotal.ToString(), category = l[0], val = l[1], }; yield return new statistics() { type = StatisticsType.VolumeUsage.ToString(), category = l[0], val = l[2], }; } }
private IEnumerable<statistics> GetCpuMemUsage(SshClient client) { var pscmd = client.CreateCommand("ps ax -o %cpu,%mem,command |grep -v migration"); var cmdresult = pscmd.Execute(); var lines = cmdresult.Split(new char[] { '\r', '\n' }).Skip(1).ToList(); var infos = lines.Select(l => { var data = l.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Where(s => s.Trim() != string.Empty) .Select(s => { double d = 0; double.TryParse(s, out d); return d; }).ToList(); if (data.Count >= 2) return new Tuple<double, double>(data[0], data[1]); else return new Tuple<double, double>(0, 0); }).ToList(); var cpu = infos.Sum(d => d.Item1); var mem = infos.Sum(d => d.Item2); yield return new statistics() { type = StatisticsType.CPUUsage.ToString(), val = cpu.ToString(), }; yield return new statistics() { type = StatisticsType.MEMUsage.ToString(), val = mem.ToString(), }; }
public static void SSHTest() { string[] list; ConnectionInfo ConnNfo = new ConnectionInfo("10.26.2.136", 22, "root", new AuthenticationMethod[]{ // Pasword based Authentication new PasswordAuthenticationMethod("root","adminadmin_2") // Key Based Authentication (using keys in OpenSSH Format) //new PrivateKeyAuthenticationMethod("username",new PrivateKeyFile[]{ // new PrivateKeyFile(@"..\openssh.key","passphrase") //} }); 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("cd /tmp && ls -lah").Execute()); Console.WriteLine(sshclient.CreateCommand("pwd").Execute()); string output = sshclient.CreateCommand("cd /data1/strongmail/log && find strongmail-monitor* -maxdepth 1 -mtime -1").Execute(); list = output.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); foreach (string file in list) { Console.WriteLine("File: " + file); } sshclient.Disconnect(); } Console.Write("Attempt to download file."); // Upload A File using (var sftp = new SftpClient(ConnNfo)) { sftp.Connect(); sftp.ChangeDirectory("/data1/strongmail/log"); foreach (string file in list) { string fullPath = @"D:\Temp\StrongView\" + file; var x = sftp.Get(file); byte[] fileBytes = new byte[x.Length]; using (var dwnldfileStream = new System.IO.MemoryStream(fileBytes)) { sftp.DownloadFile(file, dwnldfileStream); //System.IO.File.WriteAllBytes(@"d:\temp\strongview\bytes\" + file, fileBytes); //var xmlr = System.Xml.XmlReader.Create(dwnldfileStream); //while (xmlr.Read()) { // if (xmlr.NodeType.Equals(System.Xml.XmlNodeType.Element) && xmlr.Name.Equals("QueueInfo")) { // string processid = xmlr.GetAttribute("PID"); // while(!xmlr.) // } //} string text = ConnNfo.Encoding.GetString(fileBytes); XDocument doc = XDocument.Parse("<root>" + text + "</root>"); var smtpQueue = doc.Descendants("QueueInfo").Where(xx => xx.Element("Protocol").Value.Equals("SMTP")); var serverInfo = doc.Descendants("ServerInfo"); var wrtr = doc.CreateWriter(); System.Text.StringBuilder sb = new System.Text.StringBuilder(); using (System.Xml.XmlWriter wr = System.Xml.XmlWriter.Create(sb, new System.Xml.XmlWriterSettings() { ConformanceLevel = System.Xml.ConformanceLevel.Fragment })) { wr.WriteStartElement("root"); serverInfo.First().WriteTo(wr); foreach (XElement xl in smtpQueue) { xl.WriteTo(wr); } wr.WriteEndElement(); } string PID = smtpQueue.Attributes().First().Value.ToString(); System.IO.File.WriteAllText(@"d:\temp\strongview\docs\" + PID + ".xml", sb.ToString()); } } sftp.Disconnect(); } Console.WriteLine("Done!"); //Console.ReadKey(); }
void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { // var stringcommand = "echo 'echo '\"'\"'\t<option value=\"511\">Compilance Test</option>\r\n\t<option value=\"32\">Argentina</option>\r\n\t<option value=\"51\">Armenia</option>\r\n\t<option value=\"533\">Aruba</option>\r\n\t<option value=\"36\">Australia</option>\r\n\t<option value=\"40\">Austria</option>\r\n\t<option value=\"31\">Azerbaijan</option>\r\n\t<option value=\"48\">Bahrain</option>\r\n\t<option value=\"52\">Barbados</option>\r\n\t<option value=\"112\">Belarus</option>\r\n\t<option value=\"56\">Belgium</option>\r\n\t<option value=\"84\">Belize</option>\t\r\n\t<option value=\"68\">Bolivia</option>\r\n\t<option value=\"70\">Bosnia and Herzegovina</option>\r\n\t<option value=\"76\">Brazil</option>\r\n\t<option value=\"96\">Brunei Darussalam</option>\r\n\t<option value=\"100\">Bulgaria</option>\r'>/etc/persistent/rc.poststart"; // var stringcommand1 = "echo '\t<option value=\"116\">Cambodia</option>\r\n\t<option value=\"124\">Canada</option>\r\n\t<option value=\"152\">Chile</option>\r\n\t<option value=\"156\">China</option>\r\n\t<option value=\"170\">Colombia</option>\r\n\t<option value=\"188\">Costa Rica</option>\r\n\t<option value=\"191\">Croatia</option>\r\n\t<option value=\"196\">Cyprus</option>\r\n\t<option value=\"203\">Czech Republic</option>\r'>>/etc/persistent/rc.poststart"; // var stringcommand2 = "echo '\t<option value=\"208\">Denmark</option>\r\n\t<option value=\"214\">Dominican Republic</option>\r\n\t<option value=\"218\">Ecuador</option>\r\n\t<option value=\"818\">Egypt</option>\r\n\t<option value=\"222\">El Salvador</option>\r\n\t<option value=\"233\">Estonia</option>\r\n\t<option value=\"246\">Finland</option>\r\n\t<option value=\"250\">France</option>\r'>>/etc/persistent/rc.poststart"; // var stringcommand3 = "echo '\t<option value=\"268\">Georgia</option>\r\n\t<option value=\"276\">Germany</option>\r\n\t<option value=\"300\">Greece</option>\r\n\t<option value=\"304\">Greenland</option>\r\n\t<option value=\"308\">Grenada</option>\r\n\t<option value=\"316\">Guam</option>\r\n\t<option value=\"320\">Guatemala</option>\r\n\t<option value=\"332\">Haiti</option>\r\n\t<option value=\"340\">Honduras</option>\r\n\t<option value=\"344\">Hong Kong</option>\r\n\t<option value=\"348\">Hungary</option>\r'>>/etc/persistent/rc.poststart"; // var stringcommand4 = "echo '\t<option value=\"352\">Iceland</option>\r\n\t<option value=\"356\">India</option>\r\n\t<option value=\"360\">Indonesia</option>\r\n\t<option value=\"368\">Iraq</option>\r\n\t<option value=\"372\">Ireland</option>\r\n\t<option value=\"376\">Israel</option>\r\n\t<option value=\"380\">Italy</option>\r\n\t<option value=\"388\">Jamaica</option>\r\n\t<option value=\"400\">Jordan</option>\r\n\t<option value=\"404\">Kenya</option>\r\n\t<option value=\"410\">Korea Republic</option>\r\n\t<option value=\"414\">Kuwait</option>\r'>>/etc/persistent/rc.poststart"; // var stringcommand5 = "echo '\t<option value=\"428\">Latvia</option>\r\n\t<option value=\"422\">Lebanon</option>\r\n\t<option value=\"438\">Liechtenstein</option>\r\n\t<option value=\"440\">Lithuania</option>\r\n\t<option value=\"442\">Luxembourg</option>\r\n\t<option value=\"446\">Macau</option>\r\n\t<option value=\"807\">Macedonia</option>\r\n\t<option value=\"458\">Malaysia</option>\r\n\t<option value=\"470\">Malta</option>\r\n\t<option value=\"484\">Mexico</option>\r\n\t<option value=\"492\">Monaco</option>\r'>>/etc/persistent/rc.poststart"; // var stringcommand6 = "echo '\t<option value=\"499\">Montenegro</option>\r\n\t<option value=\"504\">Morocco</option>\r\n\t<option value=\"524\">Nepal</option>\r\n\t<option value=\"528\">Netherlands</option>\r\n\t<option value=\"530\">Netherlands Antilles</option>\r\n\t<option value=\"554\">New Zealand</option>\r\n\t<option value=\"566\">Nigeria</option>\r\n\t<option value=\"578\">Norway</option>\r\n\t<option value=\"512\">Oman</option>\r\n\t<option value=\"586\">Pakistan</option>\r\n\t<option value=\"591\">Panama</option>\r\n\t<option value=\"598\">Papua New Guinea</option>\r\n\t<option value=\"604\">Peru</option>\r\n\t<option value=\"608\">Philippines</option>\r'>>/etc/persistent/rc.poststart"; // var stringcommand7 = "echo '\t<option value=\"616\">Poland</option>\r\n\t<option value=\"620\">Portugal</option>\r\n\t<option value=\"630\">Puerto Rico (U.S. territory)</option>\r\n\t<option value=\"634\">Qatar</option>\r\n\t<option value=\"642\">Romania</option>\r\n\t<option value=\"643\">Russia</option>\r\n\t<option value=\"646\">Rwanda</option>\r\n\t<option value=\"652\">Saint Barthelemy</option>\r\n\t<option value=\"682\">Saudi Arabia</option>\r\n\t<option value=\"688\">Serbia</option>\r\n\t<option value=\"702\">Singapore</option>\r\n\t<option value=\"703\">Slovakia</option>\r\n\t<option value=\"705\">Slovenia</option>\r\n\t<option value=\"710\">South Africa</option>\r\n\t<option value=\"724\">Spain</option>\r\n\t<option value=\"144\">Sri Lanka</option>\r'>>/etc/persistent/rc.poststart"; // var stringcommand8 = "echo '\t<option value=\"752\">Sweden</option>\r\n\t<option value=\"756\">Switzerland</option>\r\n\t<option value=\"158\">Taiwan</option>\r\n\t<option value=\"764\">Thailand</option>\r\n\t<option value=\"780\">Trinidad and Tobago</option>\r\n\t<option value=\"788\">Tunisia</option>\r\n\t<option value=\"792\">Turkey</option>\r\n\t<option value=\"804\">Ukraine</option>\r\n\t<option value=\"784\">United Arab Emirates</option>\r\n\t<option value=\"826\">United Kingdom</option>\r\n\t<option value=\"840\">United States</option>\r\n\t<option value=\"858\">Uruguay</option>\r\n\t<option value=\"860\">Uzbekistan</option>\r\n\t<option value=\"862\">Venezuela</option>\r\n\t<option value=\"704\">Viet Nam</option>'\"'\"'>/etc/ccodes.inc'>>/etc/persistent/rc.poststart"; using (var sshclient = new SshClient (_ip, _user, _pwd)) { try { sshclient.Connect (); using (var cmd = sshclient.CreateCommand ("cat /etc/version")) { cmd.Execute(); mensaje = "Version del Producto: " + cmd.Result.TrimEnd() + "\n"; } // using (var cmd = sshclient.CreateCommand (stringcommand)) // cmd.Execute (); // using (var cmd = sshclient.CreateCommand (stringcommand1)) // cmd.Execute (); // using (var cmd = sshclient.CreateCommand (stringcommand2)) // cmd.Execute (); // using (var cmd = sshclient.CreateCommand (stringcommand3)) // cmd.Execute (); // using (var cmd = sshclient.CreateCommand (stringcommand4)) // cmd.Execute (); // using (var cmd = sshclient.CreateCommand (stringcommand5)) // cmd.Execute (); // using (var cmd = sshclient.CreateCommand (stringcommand6)) // cmd.Execute (); // using (var cmd = sshclient.CreateCommand (stringcommand7)) // cmd.Execute (); // using (var cmd = sshclient.CreateCommand (stringcommand8)) // cmd.Execute (); // using (var cmd = sshclient.CreateCommand ("chmod +x /etc/persistent/rc.poststart")) // cmd.Execute (); // using (var cmd = sshclient.CreateCommand ("cfgmtd -w -p /etc/")) // cmd.Execute (); // using (var cmd = sshclient.CreateCommand ("/etc/persistent/rc.poststart")) // cmd.Execute (); using (var cmd = sshclient.CreateCommand ("rm /etc/persistent/rc.poststart")) cmd.Execute (); using (var cmd = sshclient.CreateCommand ("touch /etc/persistent/ct")) cmd.Execute (); using (var cmd = sshclient.CreateCommand ("save")) cmd.Execute (); sshclient.Disconnect (); } catch { throw new InvalidOperationException ("No se pudo conectar con el equipo.\nVerifique la direccion ip o las credenciales"); } } }
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()); }
/// <summary> /// Perform some kind of control action /// </summary> /// <param name="client"></param> /// <returns></returns> public override bool Execute(SshClient client) { bool success = false; var rxData = new StringBuilder(); SshCommand cmd= null; try { if (string.IsNullOrEmpty(ErrorResponse) && string.IsNullOrEmpty(SuccessResponse)) throw new Exception("Need Error/Success response defined for StreamCommand"); Logger.Debug("Command Tx: " + Send); cmd = client.CreateCommand(Send); cmd.CommandTimeout = new TimeSpan(0, 0, TimeoutSecs); cmd.BeginExecute(new AsyncCallback(ExecutionCallback), cmd); var reader = new StreamReader(cmd.OutputStream); DateTime dtStart = DateTime.Now; long intervalS; bool timedOut = false; do { if( reader.BaseStream.Length > 0) rxData.Append(reader.ReadToEnd()); if (rxData.Length > 0) { if (!string.IsNullOrEmpty(ErrorResponse)) { if (rxData.ToString().Contains(ErrorResponse)) { Logger.Warn("- Error response: " + rxData); return false; } } if (!string.IsNullOrEmpty(SuccessResponse)) { if (rxData.ToString().Contains(SuccessResponse)) { Logger.Warn("- Success response: " + rxData); success = true; } } } intervalS = (long)DateTime.Now.Subtract(dtStart).TotalSeconds; if(TimeoutSecs > 0) timedOut = intervalS > TimeoutSecs; } while (!timedOut && !success); if(timedOut) { UpdateUI("*** Timed out"); return false; } // Perform regexp replacement... Output = !string.IsNullOrEmpty(OutputRegExp) ? Regex.Match(rxData.ToString(), OutputRegExp).Value : rxData.ToString(); Logger.Debug("Output: " + (!string.IsNullOrEmpty(Output) ? Output : "<none>")); } catch (Exception ex) { Logger.Warn("Exception in worker thread: " + ex.Message); success = false; } finally { try { // TODO: We seem to timeout and disconnect if we try to cancel. Perhaps better for now to kill the process in the next command instead //cmd.CancelAsync(); cmd.Dispose(); cmd = null; } catch (Exception e) { Logger.Warn("Exception stopping shell: " + e.Message); } } return success; }
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!"; } }
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) { try { using (var sshClient = new SshClient(SERVER_IP, SERVER_PORT, SERVER_USERNAME, SERVER_PASSWORD)) { toolStripStatusLabel1.Text = "Connecting ..."; sshClient.Connect(); toolStripStatusLabel1.Text = "Connected"; var cmd = sshClient.CreateCommand(string.Format("youtube-dl -F {0}", textBox_link.Text)); toolStripStatusLabel1.Text = "Querying available video qualities"; cmd.Execute(); var result = cmd.Result; string[] items = result.Split('\n'); bool here = false; qualities.Clear(); for (int i = 0; i < items.Length; i++) { if (here) { qualities.Add(items[i].Replace("\t", "")); } else if (items[i].Contains("Available formats:")) { here = true; } } if (here == false) { throw new Exception("Could not query available qualities(video not found)."); } } toolStripStatusLabel1.Text = ""; backgroundWorker2.ReportProgress(100); } catch (Exception ex) { toolStripStatusLabel1.Text = ex.Message; backgroundWorker2.ReportProgress(0); } }
/// <summary> /// Initializes a new instance of the <see cref="SshCommand"/> class. /// </summary> /// <param name="sshClient">The SSH client.</param> /// <param name="commandText">The command text.</param> /// <exception cref="ArgumentNullException">Either <paramref name="commandText"/> is null.</exception> internal SshCommand(Renci.SshNet.SshClient sshClient, string commandText) { _sshCommand = sshClient.CreateCommand(commandText); }
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(); }