public void CleanCurrentFolder()
 {
     using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         client.Connect();
         client.RunCommand("rm -rf *");
         client.Disconnect();
     }
 }
Example #2
0
 protected void RebootButton_Click(object sender, EventArgs e)
 {
     try
     {
         using (var client = new SshClient("ra-jetson.duckdns.org", "ubuntu", "savingL1v3s"))
         {
             client.Connect();
             client.RunCommand("sudo /home/ubuntu/Desktop/bandhan/SQL-Scripts/./RightAlertRemoteRebootIssued-SQL"); // SSH Command Here
             client.RunCommand("sudo reboot"); // SSH Command Here
             client.Disconnect();
         }
     }
     catch (Exception ex)
     {
         Response.Redirect("Down.html");
     }
 }
Example #3
0
        public void Test_Run_SingleCommand()
        {
            var host = Resources.HOST;
            var username = Resources.USERNAME;
            var password = Resources.PASSWORD;

            using (var client = new SshClient(host, username, password))
            {
                #region Example SshCommand RunCommand Result
                client.Connect();

                var testValue = Guid.NewGuid().ToString();
                var command = client.RunCommand(string.Format("echo {0}", testValue));
                var result = command.Result;
                result = result.Substring(0, result.Length - 1);    //  Remove \n character returned by command

                client.Disconnect();
                #endregion

                Assert.IsTrue(result.Equals(testValue));
            }
        }
        public void Test_Ssh_Connect_Via_HttpProxy()
        {
            var connInfo = new PasswordConnectionInfo(Resources.HOST, Resources.USERNAME, Resources.PASSWORD, ProxyTypes.Http, Resources.PROXY_HOST, int.Parse(Resources.PROXY_PORT));
            using (var client = new SshClient(connInfo))
            {
                client.Connect();

                var ret = client.RunCommand("ls -la");

                client.Disconnect();
            }
        }
Example #5
0
 public void RunCommandTest()
 {
     ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
     SshClient target = new SshClient(connectionInfo); // TODO: Initialize to an appropriate value
     string commandText = string.Empty; // TODO: Initialize to an appropriate value
     SshCommand expected = null; // TODO: Initialize to an appropriate value
     SshCommand actual;
     actual = target.RunCommand(commandText);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
Example #6
0
        protected override void OnInit()
        {
            base.OnInit();

            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                client.Connect();
                client.RunCommand("rm -rf *");
                client.Disconnect();
            }
        }
        private void DoWork()
        {
            if (_sshLoad.Count > 0 && !_forceStop)
            {
                var line = _sshLoad[_numberOfRecordWorking];

                if (_numberOfRecordWorking < _numberOfRecords)
                {
                    _numberOfRecordWorking++;
                }

                Invoke(new MethodInvoker(() =>
                {
                    lblChecking.Text =
                        $"Running: {_numberOfRecordWorking}/{_numberOfRecords}";

                    prbRunningStatus.Value = _numberOfRecordWorking;
                }));

                var arr = line.Split('|');

                if (arr.Length <= 2)
                {
                    return;
                }

                var ip   = arr[0];
                var user = arr[1];
                var pass = arr[2];

                Invoke(new MethodInvoker(() =>
                {
                    lblIpRunning.Text = $"{ip} is checking...";
                }));

                if (string.IsNullOrWhiteSpace(ip) || string.IsNullOrWhiteSpace(user) ||
                    string.IsNullOrWhiteSpace(pass))
                {
                    return;
                }

                using (var sshClient = new SshClient(ip, user, pass))
                {
                    try
                    {
                        sshClient.ConnectionInfo.Timeout = new TimeSpan(0, 0, (int)numericUpDown1.Value);


                        Console.WriteLine($"{ip} is connecting...");

                        sshClient.Connect();

                        if (sshClient.IsConnected)
                        {
                            Console.WriteLine($"{ip} has connected.");

                            var result = sshClient.RunCommand("curl http://icanhazip.com").Result;
                            if (!string.IsNullOrWhiteSpace(result))
                            {
                                var country = "UNKNOWN";

                                var ipFormat = new MakeRangeIp.IpFormat(ip);

                                var local =
                                    _geoIpCountryList.FirstOrDefault(
                                        x => x.IpBegin.Number <= ipFormat.Number && ipFormat.Number <= x.IpEnd.Number);

                                if (local != null)
                                {
                                    country = $"{local.Country.CountryName} ({local.Country.ISOCode})";
                                }

                                _sshFreshs.Add($"{ip}|{user}|{pass}|{country}");
                            }
                            else
                            {
                                _sshFails.Add($"{line}(Cannot get data from url test)");
                            }

                            sshClient.Disconnect();

                            Console.WriteLine($"{ip} was disconected.");
                        }
                        else
                        {
                            Console.WriteLine($"{ip} cannot connect.");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"{ip} has failed: {ex.Message}");

                        _sshFails.Add($"{line}({ex.Message})");
                    }

                    _numberOfRecordFinished++;

                    Invoke(new MethodInvoker(() =>
                    {
                        prbChecked.Value = _numberOfRecordFinished;
                        lblChecked.Text  = $"Checked: {_numberOfRecordFinished}/{_numberOfRecords} | Fresh: {_sshFreshs.Count} | Fail: {_sshFails.Count}";
                    }));
                }
            }

            if (_forceStop)
            {
                Invoke(new MethodInvoker(() =>
                {
                    btnRun.Text            = @"Run Check";
                    lblIpRunning.Text      = @"Stopped";
                    prbRunningStatus.Value = prbRunningStatus.Maximum;
                    InitControl(true);
                }));
            }

            if (_numberOfRecordFinished >= _numberOfRecords)
            {
                Invoke(new MethodInvoker(() =>
                {
                    InitControl(true);
                }));
            }
        }
        public void Test_Execute_Command_ExitStatus()
        {
            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                client.Connect();

                var cmd = client.RunCommand("exit 128");
                Assert.IsTrue(cmd.ExitStatus == 128);

                client.Disconnect();
            }
        }
Example #9
0
        private static void Run(Options options)
        {
            // Connection information
            var user        = options.UserName;
            var host        = options.Host;
            var attempts    = 0;
            var success     = false;
            var match       = "";
            var begin       = DateTime.Now.Ticks;
            var noOfThreads = options.Threads;

            Console.WriteLine("================================================================");
            Console.WriteLine(" SSH Password Cracker Console v. 0.2.4.");
            Console.WriteLine("================================================================");
            Console.WriteLine();

            var list = File.ReadAllLines(options.PasswordList);

            Console.WriteLine("Using wordlist: " + options.PasswordList +
                              $" with {list.Length} words and {noOfThreads} threads. This might take some time.");

            var opts = new ParallelOptions
            {
                MaxDegreeOfParallelism = noOfThreads
            };

            Parallel.ForEach(list, opts, (w, loopState) =>
            {
                attempts++;

                try
                {
                    //Set up the SSH connection
                    using (var client = new SshClient(host, user, w))
                    {
                        //Start the connection
                        client.Connect();
                        if (options.Verbose)
                        {
                            Console.WriteLine("Connected with " + w);
                        }
                        var output = client.RunCommand("echo test");
                        client.Disconnect();
                        Console.WriteLine(output.Result);

                        success = true;
                        match   = w;
                        loopState.Stop();
                    }
                }
                catch
                {
                    // continue silently
                    if (options.Verbose)
                    {
                        Console.WriteLine("Tried " + w + " with no success");
                    }
                }
            });

            var elapsed = TimeSpan.FromTicks(DateTime.Now.Ticks - begin);

            if (success)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"Done after {attempts} tries. Match:[{match}] for user:[{user}]. Elapsed: {elapsed:g}");
                Console.ResetColor();
            }
            else
            {
                Console.WriteLine($"Done after {attempts} tries. No matches found. Try a different wordlist. Elapsed: {elapsed:g}");
            }

            if (Debugger.IsAttached)
            {
                Console.WriteLine("Hit any key...");
                Console.ReadKey();
            }
        }
Example #10
0
        private async Task OnEvent(WatcherEvent <V1Secret> e)
        {
            var id   = KubernetesObjectId.For(e.Item.Metadata());
            var item = e.Item;

            _logger.LogTrace("[{eventType}] {kind} {@id}", e.Type, e.Item.Kind, id);

            if (e.Type != WatchEventType.Added && e.Type != WatchEventType.Modified)
            {
                return;
            }
            if (!e.Item.Metadata.ReflectionAllowed() || !e.Item.Metadata.FortiReflectionEnabled())
            {
                return;
            }
            if (!e.Item.Type.Equals("kubernetes.io/tls", StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }


            var caCrt    = Encoding.Default.GetString(item.Data["ca.crt"]);
            var tlsCrt   = Encoding.Default.GetString(item.Data["tls.crt"]);
            var tlsKey   = Encoding.Default.GetString(item.Data["tls.key"]);
            var tlsCerts = tlsCrt.Split(new[] { "-----END CERTIFICATE-----" }, StringSplitOptions.RemoveEmptyEntries)
                           .Select(s => s.TrimStart())
                           .Where(s => !string.IsNullOrWhiteSpace(s))
                           .Select(s => $"{s}-----END CERTIFICATE-----")
                           .ToList();


            var hostSecretIds = item.Metadata.FortiReflectionHosts().Select(s => new KubernetesObjectId(s)).ToList();
            var fortiCertName = item.Metadata.FortiCertificate();
            var fortiCertId   = !string.IsNullOrWhiteSpace(fortiCertName)
                ? fortiCertName
                : item.Metadata.Name.Substring(0, Math.Min(item.Metadata.Name.Length, 30));

            foreach (var hostSecretId in hostSecretIds)
            {
                _logger.LogDebug(
                    "Reflecting {secretId} to FortiOS device using host secret {hostSecretId}.",
                    id, hostSecretId, hostSecretId);
                string fortiHost;
                string fortiUsername;
                string fortiPassword;
                try
                {
                    var hostSecret = await _apiClient.ReadNamespacedSecretAsync(hostSecretId.Name,
                                                                                string.IsNullOrWhiteSpace(hostSecretId.Namespace)
                                                                                ?e.Item.Metadata.NamespaceProperty
                                                                                : hostSecretId.Namespace);

                    if (hostSecret.Data is null || !hostSecret.Data.Keys.Any())
                    {
                        _logger.LogWarning("Cannot reflect {secretId} to {hostSecretId}. " +
                                           "Host secret {hostSecretId} has no data.",
                                           id, hostSecretId, hostSecretId);
                        continue;
                    }

                    fortiHost = hostSecret.Data.ContainsKey("host")
                        ? Encoding.Default.GetString(hostSecret.Data["host"])
                        : null;
                    fortiUsername = hostSecret.Data.ContainsKey("username")
                        ? Encoding.Default.GetString(hostSecret.Data["username"])
                        : null;
                    fortiPassword = hostSecret.Data.ContainsKey("password")
                        ? Encoding.Default.GetString(hostSecret.Data["password"])
                        : null;
                }
                catch (HttpOperationException ex) when(ex.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    _logger.LogWarning(
                        "Cannot reflect {secretId} to {hostSecretId}. Host secret {hostSecretId} not found.",
                        id, hostSecretId, hostSecretId);

                    continue;
                }

                if (string.IsNullOrWhiteSpace(fortiHost) || string.IsNullOrWhiteSpace(fortiUsername) ||
                    string.IsNullOrWhiteSpace(fortiPassword))
                {
                    _logger.LogWarning(
                        "Cannot reflect {secretId} to FortiOS device using host secret {hostSecretId}. " +
                        "Host secret {hostSecretId} must contain 'host', 'username' and 'password' values.",
                        id, hostSecretId, hostSecretId);
                    continue;
                }

                var hostParts = fortiHost.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries)
                                .Select(s => s.Trim())
                                .Where(s => !string.IsNullOrWhiteSpace(s)).ToList();
                if (!hostParts.Any() || hostParts.Count > 2)
                {
                    _logger.LogWarning(
                        "Cannot reflect {secretId} to FortiOS device using host secret {hostSecretId}. " +
                        "Host secret {hostSecretId} contains invalid 'host' data. " +
                        "'host' must be in the format 'host:port' where port is optional.",
                        id, hostSecretId, hostSecretId);
                }

                var hostPort = hostParts.Count < 2 ? 22 : int.TryParse(hostParts.Last(), out var port) ? port : 22;

                using var client = new SshClient(hostParts.First(), hostPort, fortiUsername, fortiPassword)
                      {
                          ConnectionInfo =
                          {
                              Timeout = TimeSpan.FromSeconds(10)
                          }
                      };

                try
                {
                    _logger.LogDebug("Connecting for FortiOS device at {host}", fortiHost);
                    client.Connect();
                }
                catch (Exception exception)
                {
                    _logger.LogError(exception,
                                     "Cannot reflect {secretId} to FortiOS device using host secret {hostSecretId} due to exception.",
                                     id, hostSecretId);
                    continue;
                }


                _logger.LogDebug("Checking for certificate {certId} on FortiOS device {host}", fortiCertId, fortiHost);
                string checkOutput;
                await using (var shell = client.CreateShellStream(nameof(FortiMirror), 128, 1024, 800, 600, 1024))
                {
                    var lastLine      = string.Empty;
                    var outputBuilder = new StringBuilder();
                    shell.WriteLine("config vpn certificate local");
                    shell.WriteLine($"edit {fortiCertId}");
                    shell.WriteLine("show full");
                    shell.WriteLine("end");

                    while (!(lastLine.Contains("#") && lastLine.Contains("end")))
                    {
                        lastLine = shell.ReadLine();
                        outputBuilder.AppendLine(lastLine);
                    }

                    shell.Close();
                    checkOutput = outputBuilder.ToString();
                }

                var localCertificateUpToDate = true;

                if (!string.IsNullOrWhiteSpace(tlsKey))
                {
                    if (checkOutput.Contains("unset private-key"))
                    {
                        localCertificateUpToDate = false;
                    }
                }

                if (!checkOutput.Contains("set certificate", StringComparison.InvariantCultureIgnoreCase))
                {
                    localCertificateUpToDate = false;
                }
                else
                {
                    var remoteCertificate = checkOutput.Substring(checkOutput.IndexOf("set certificate \"",
                                                                                      StringComparison.InvariantCultureIgnoreCase));
                    remoteCertificate = remoteCertificate.Replace("set certificate \"", string.Empty,
                                                                  StringComparison.InvariantCultureIgnoreCase);
                    remoteCertificate = remoteCertificate.Substring(0,
                                                                    remoteCertificate.IndexOf("\"", StringComparison.InvariantCultureIgnoreCase));
                    remoteCertificate = remoteCertificate.Replace("\r", string.Empty);

                    if (!tlsCerts.Select(s => s.Replace("\r", string.Empty)).Contains(remoteCertificate))
                    {
                        localCertificateUpToDate = false;
                    }
                }

                var success = true;

                if (!localCertificateUpToDate)
                {
                    var commandBuilder = new StringBuilder();
                    commandBuilder.AppendLine("config vpn certificate local");
                    commandBuilder.AppendLine($"edit {fortiCertId}");
                    commandBuilder.AppendLine($"set private-key \"{tlsKey}\"");
                    commandBuilder.AppendLine($"set certificate \"{tlsCrt}\"");
                    commandBuilder.AppendLine("end");
                    var command = client.RunCommand(commandBuilder.ToString());
                    if (command.ExitStatus != 0 || !string.IsNullOrWhiteSpace(command.Error))
                    {
                        _logger.LogWarning(
                            "Checking for certificate {certId} could not be installed on FortiOS device {host} due to error: {error}",
                            id, fortiHost, command.Error);
                        success = false;
                    }
                }

                if (!localCertificateUpToDate && success)
                {
                    var caCerts = tlsCerts.ToList();
                    if (!string.IsNullOrWhiteSpace(caCrt))
                    {
                        caCerts.Add(caCrt);
                    }
                    var caId = 0;
                    for (var i = 0; i < caCerts.Count; i++)
                    {
                        _logger.LogDebug("Installing CA certificate {index} for {certId} on FortiOS device {host}",
                                         i + 1, id, fortiHost);

                        var commandBuilder = new StringBuilder();
                        commandBuilder.AppendLine("config vpn certificate ca");
                        commandBuilder.AppendLine(
                            $"edit {fortiCertId}_CA{(caId == 0 ? string.Empty : caId.ToString())}");
                        commandBuilder.AppendLine($"set ca \"{tlsCerts[i]}\"");
                        commandBuilder.AppendLine("end");
                        var command = client.RunCommand(commandBuilder.ToString());
                        if (command.ExitStatus == 0 && string.IsNullOrWhiteSpace(command.Error))
                        {
                            caId++;
                            continue;
                        }

                        if (command.Error.Contains("This CA certificate is duplicated."))
                        {
                            _logger.LogWarning(
                                "Skipping CA certificate {index} since it is duplicated by another certificate.",
                                i + i);
                        }
                        else if (command.Error.Contains("Input is not a valid CA certificate."))
                        {
                            _logger.LogDebug("Skipping CA certificate {index} since it is not a valid CA certificate.",
                                             i + i);
                        }
                        else
                        {
                            _logger.LogWarning("Could not install CA {index} certificate due to error: {response}",
                                               i + 1, command.Result);
                            success = false;
                        }
                    }
                }


                if (!success)
                {
                    _logger.LogError(
                        "Reflecting {secretId} to FortiOS device using host secret {hostSecretId} completed with errors.",
                        id, hostSecretId);
                }
                else if (!localCertificateUpToDate)
                {
                    _logger.LogInformation("Reflected {secretId} to FortiOS device using host secret {hostSecretId}.",
                                           id, hostSecretId);
                }
            }
        }
Example #11
0
        private static string runCommand(string command, SshClient client)
        {
            SshCommand sshCommand = client.RunCommand(command);

            return(sshCommand.Result.Trim());
        }
Example #12
0
        private static Task HandleOneHostAsync(ConnectionInfo connectionInfo, IList <string> pathList)
        {
            // 构造在主线程构造,防止在多个线程连接多个节点,信息冲突
            if (CommandLine.IsVerbose)
            {
                Console.WriteLine($"正在连接 {connectionInfo.Host}");
            }

            ScpClient scpClient = new ScpClient(connectionInfo);
            SshClient sshClient = new SshClient(connectionInfo);

            scpClient.Connect();
            sshClient.Connect();
            if (CommandLine.IsVerbose)
            {
                Console.WriteLine($"连接成功 {connectionInfo.Host}");
            }

            return(Task.Factory.StartNew(() => {
                foreach (string s in pathList)
                {
                    string parent = Path.GetDirectoryName(s);
                    if (CommandLine.IsVerbose)
                    {
                        Console.WriteLine($"正在转输 {s} 至 {connectionInfo.Host}");
                    }

                    // 文件操作
                    if (File.Exists(s))
                    {
                        FileInfo fileInfo = new FileInfo(s);
                        sshClient.RunCommand($"mkdir -p {parent}");
                        scpClient.Upload(fileInfo, s);
                        Console.WriteLine($"文件完成:远程主机{connectionInfo.Host} 远程路径{s} 大小 {fileInfo.Length} 字节");
                    }
                    // 文件夹操作
                    else if (Directory.Exists(s))
                    {
                        DirectoryInfo directoryInfo = new DirectoryInfo(s);
                        sshClient.RunCommand($"mkdir -p {parent}");
                        if (CommandLine.ExistArgument <DeleteFolderArgument>())
                        {
                            sshClient.RunCommand($"rm -rf {s}");
                            Console.WriteLine($"删除文件夹:远程主机{connectionInfo.Host} 远程路径{s}");
                        }
                        scpClient.Upload(directoryInfo, s);
                        Console.WriteLine($"文件夹完成:远程主机{connectionInfo.Host} 远程路径{s}");
                    }
                }

                Task.Factory.StartNew(() => {
                    sshClient.Dispose();
                    if (CommandLine.IsVerbose)
                    {
                        Console.WriteLine($"SSH连接断开:{connectionInfo.Host}");
                    }
                });
                Task.Factory.StartNew(() => {
                    scpClient.Dispose();
                    if (CommandLine.IsVerbose)
                    {
                        Console.WriteLine($"SCP连接断开:{connectionInfo.Host}");
                    }
                });
            }));
        }
Example #13
0
        private void button1_Click(object sender, EventArgs e)
        {
            var maCommande = MonLienSecure.RunCommand(comboBoxCommand.Text);

            textHistorique.AppendText(maCommande.Result + Environment.NewLine);
        }
Example #14
0
        public void PublishZip(Stream stream, string destinationFolder, string destinationfileName, Func <bool> continuetask = null)
        {
            bool CheckCancel()
            {
                if (continuetask != null)
                {
                    var canContinue = continuetask();
                    if (!canContinue)
                    {
                        return(true);
                    }
                }

                return(false);
            }

            if (!destinationFolder.EndsWith("/"))
            {
                destinationFolder = destinationFolder + "/";
            }
            //按照项目分文件夹
            var projectPath = destinationFolder + PorjectName + "/";

            //再按发布版本分文件夹
            destinationFolder = projectPath + ClientDateTimeFolderName + "/";

            //创建项目根目录
            var deploySaveFolder = projectPath + "deploy/";

            try
            {
                if (IsSelect)
                {
                    if (!_sftpClient.Exists(deploySaveFolder))
                    {
                        _logger($"The first time Can not use select file deploy", LogLevel.Error);
                        return;
                    }
                }
                CreateServerDirectoryIfItDoesntExist(deploySaveFolder);
                Upload(stream, destinationFolder, destinationfileName);
            }
            catch (Exception)
            {
                if (CheckCancel())
                {
                    return;
                }

                throw;
            }

            if (!_sftpClient.Exists(destinationfileName))
            {
                _logger($"upload fail, {destinationfileName} not exist!", LogLevel.Error);
                return;
            }

            if (CheckCancel())
            {
                return;
            }
            //创建args文件 antdeploy_args
            var argsFilePath = destinationFolder + "antdeploy_args";

            CreateArgsFile(argsFilePath);

            _logger($"unzip -o -q {destinationFolder + destinationfileName} -d publish/", LogLevel.Info);
            var unzipresult = _sshClient.RunCommand($"cd {destinationFolder} && unzip -o -q {destinationfileName} -d publish/");

            if (unzipresult.ExitStatus != 0)
            {
                _logger($"excute zip command error,return status is not 0", LogLevel.Error);
                _logger($"please check 【zip】 is installed in your server!", LogLevel.Error);
                return;
            }

            if (CheckCancel())
            {
                return;
            }

            var publishFolder = $"{destinationFolder}publish/";


            if (!_sftpClient.Exists("publish"))
            {
                _logger($"unzip fail: {publishFolder}", LogLevel.Error);
                return;
            }
            _logger($"unzip success: {publishFolder}", LogLevel.Info);

            var isExistDockFile = true;

            if (!Increment)
            {
                //如果没有DockerFile 创建默认的
                var dockFilePath  = publishFolder + "Dockerfile";
                var dockFilePath2 = "publish/Dockerfile";
                isExistDockFile = _sftpClient.Exists(dockFilePath2);
                if (!isExistDockFile)
                {
                    var createDockerFileResult = CreateDockerFile(dockFilePath);
                    if (!createDockerFileResult)
                    {
                        return;
                    }
                }

                if (CheckCancel())
                {
                    return;
                }
            }

            //复制 覆盖 文件到项目下的 deploy目录
            CopyCpFolder(publishFolder, deploySaveFolder);
            if (CheckCancel())
            {
                return;
            }

            if (Increment)
            {
                var incrementFoler = $"{destinationFolder}increment/";

                //增量发布 备份全部文件到 increment 文件夹
                _logger($"Increment deploy start backup to [{incrementFoler}]", LogLevel.Info);

                CopyCpFolder(deploySaveFolder, incrementFoler);

                _logger($"Increment deploy success backup to [{incrementFoler}]", LogLevel.Info);
                if (CheckCancel())
                {
                    return;
                }
            }


            //执行Docker命令
            _sftpClient.ChangeDirectory(RootFolder);
            ChangeToFolder(deploySaveFolder);
            DoDockerCommand(deploySaveFolder, false, !isExistDockFile, publishName: "");
        }
 private static SshCommand RunCommand(SshClient sshClient, string command) =>
 sshClient.RunCommand(command);
Example #16
0
        public void Test_Execute_Command_ExitStatus()
        {
            using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                #region Example SshCommand RunCommand ExitStatus
                client.Connect();

                var cmd = client.RunCommand("exit 128");
                
                Console.WriteLine(cmd.ExitStatus);

                client.Disconnect();
                #endregion

                Assert.IsTrue(cmd.ExitStatus == 128);
            }
        }
Example #17
0
        private void ItemBegin_ItemActivated(object sender, Qios.DevSuite.Components.QCompositeEventArgs e)
        {
            if (FormDialog.simbolDialog == true)
            {
                resultDict = load_xml();

                bool success = false;
                Lblmessage.Visible = true;
                Lblmessage.Text    = "Calculating, please wait...";
                TxtName            = DateTime.Now.ToString("MMddhhmmss"); //设置生成的txt文件的名字
                outPutPath         = FormDialog.OutputFilePath_global + @"\" + TxtName;
                if (FormLogin.if_online)
                {
                    //    Thread thread = new Thread(delegate ()
                    //    {
                    //        var testCmd = sshClient.RunCommand("mkdir " + "output");
                    //        if (!string.IsNullOrWhiteSpace(testCmd.Error))
                    //            Console.WriteLine(testCmd.Error);
                    //        else
                    //            Console.WriteLine(testCmd.Result);
                    //        string outPutPath_online = "/home/" + userName + "/output/" + TxtName;
                    //        string inputPath = "/home/" + userName + "/input";
                    //        sshClient.RunCommand("mkdir " + outPutPath_online);
                    //        send_online(FormDialog.AllUploadFiles, FormDialog.AllRecievePaths); //把本地文件全部发送到服务器上
                    //        calcute_online(inputPath);
                    //        //sshClient.RunCommand("docker run -v " + inputPath + ":/classification_sample/input -v " + outPutPath + ":/classification_sample/output -e PYTHONUNBUFFERED=0 phasenet_model_cross_entropy_ai_picking python3 classification_sample -i input -m  inference_graph.xml -d CPU -dt " + FormDialog.AllFileType + " -o output -ot csv -pl");
                    //        success = download(outPutPath_online);

                    //        if (success)
                    //        {
                    //            //Lblmessage.Visible = false;
                    //            Lblmessage.Text = "Connected";
                    //            ItemResult.Enabled = true;
                    //            ItemChart.Enabled = true;
                    //        }
                    //        else
                    //        {
                    //            Lblmessage.Text = "Sorry,failed to calculate...";
                    //        }
                    //    });
                    var testCmd = sshClient.RunCommand("mkdir " + "output");
                    if (!string.IsNullOrWhiteSpace(testCmd.Error))
                    {
                        Console.WriteLine(testCmd.Error);
                    }
                    else
                    {
                        Console.WriteLine(testCmd.Result);
                    }
                    outPutPath_online = "/home/" + userName + "/output/" + TxtName;
                    string inputPath_online = "/home/" + userName + "/input";
                    sshClient.RunCommand("mkdir " + outPutPath_online);
                    send_online(FormDialog.AllUploadFiles, FormDialog.AllFileName); //把本地文件全部发送到服务器上
                    calcute_online(inputPath_online, outPutPath_online);
                    //sshClient.RunCommand("docker run -v " + inputPath + ":/classification_sample/input -v " + outPutPath + ":/classification_sample/output -e PYTHONUNBUFFERED=0 phasenet_model_cross_entropy_ai_picking python3 classification_sample -i input -m  inference_graph.xml -d CPU -dt " + FormDialog.AllFileType + " -o output -ot csv -pl");
                    success = download(outPutPath_online);

                    if (success)
                    {
                        //Lblmessage.Visible = false;
                        Lblmessage.Text    = "Connected";
                        ItemResult.Enabled = true;
                        ItemChart.Enabled  = true;
                    }
                    else
                    {
                        Lblmessage.Text = "Sorry,failed to calculate...";
                    }
                }
                else
                {
                    send(FormDialog.AllUploadFiles, FormDialog.AllRecievePaths); //把本地文件全部发送到服务器上
                    success = calculate();                                       //开始计算

                    //下载结束后,关闭提示
                    if (success)
                    {
                        Lblmessage.Visible = false;
                    }
                }


                //inputFileName = FormDialog.AllFileName;  //文件路径全赋给inputfilepath

                simbolCalculate = true;
                FormDialog.AllUploadFiles.Clear();   //发布完之后清空路径
                FormDialog.AllRecievePaths.Clear();  //发布完之后清空路径
            }
            else
            {
                MessageBox.Show("Please add files first", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #18
0
 public void RunCommand_CommandText_NeverConnected()
 {
     using (var client = new SshClient(Resources.HOST, Resources.USERNAME, "invalid password"))
     {
         try
         {
             client.RunCommand("ls");
             Assert.Fail();
         }
         catch (SshConnectionException ex)
         {
             Assert.IsNull(ex.InnerException);
             Assert.AreEqual("Client not connected.", ex.Message);
         }
     }
 }
Example #19
0
 private static void RemoveAllFiles()
 {
     using (var client = new SshClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         client.Connect();
         client.RunCommand("rm -rf *");
         client.Disconnect();
     }
 }
Example #20
0
 internal void execute(SshClient client)
 {
     client.RunCommand(String.Format("echo {0} > /proc/power/relay{1}", On ? "1" : "0", Index));
 }