private void Arrange()
        {
            var random = new Random();

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelSessionAMock = new Mock<IChannelSession>(MockBehavior.Strict);
            _channelSessionBMock = new Mock<IChannelSession>(MockBehavior.Strict);
            _commandText = random.Next().ToString(CultureInfo.InvariantCulture);
            _encoding = Encoding.UTF8;
            _asyncResultA = null;
            _asyncResultB = null;

            var seq = new MockSequence();
            _sessionMock.InSequence(seq).Setup(p => p.CreateChannelSession()).Returns(_channelSessionAMock.Object);
            _channelSessionAMock.InSequence(seq).Setup(p => p.Open());
            _channelSessionAMock.InSequence(seq).Setup(p => p.SendExecRequest(_commandText))
                .Returns(true)
                .Raises(c => c.Closed += null, new ChannelEventArgs(5));
            _channelSessionAMock.InSequence(seq).Setup(p => p.Dispose());

            _sshCommand = new SshCommand(_sessionMock.Object, _commandText, _encoding);
            _asyncResultA = _sshCommand.BeginExecute();
            _sshCommand.EndExecute(_asyncResultA);

            _sessionMock.InSequence(seq).Setup(p => p.CreateChannelSession()).Returns(_channelSessionBMock.Object);
            _channelSessionBMock.InSequence(seq).Setup(p => p.Open());
            _channelSessionBMock.InSequence(seq).Setup(p => p.SendExecRequest(_commandText)).Returns(true);
        }
コード例 #2
0
ファイル: SshCommandTest.cs プロジェクト: pecegit/sshnet
 public void CancelAsyncTest()
 {
     Session session = null; // TODO: Initialize to an appropriate value
     string commandText = string.Empty; // TODO: Initialize to an appropriate value
     SshCommand target = new SshCommand(session, commandText); // TODO: Initialize to an appropriate value
     target.CancelAsync();
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
コード例 #3
0
        private void Arrange()
        {
            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _commandText = new Random().Next().ToString(CultureInfo.InvariantCulture);
            _encoding = Encoding.UTF8;
            _asyncResult = null;

            _sshCommand = new SshCommand(_sessionMock.Object, _commandText, _encoding);
        }
コード例 #4
0
        protected override void OnInit()
        {
            base.OnInit();

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _commandText = new Random().Next().ToString(CultureInfo.InvariantCulture);
            _encoding = Encoding.UTF8;
            _channelSessionMock = new Mock<IChannelSession>(MockBehavior.Strict);

            _sshCommand = new SshCommand(_sessionMock.Object, _commandText, _encoding);
        }
コード例 #5
0
ファイル: SshCommandTest.cs プロジェクト: pecegit/sshnet
 public void BeginExecuteTest1()
 {
     Session session = null; // TODO: Initialize to an appropriate value
     string commandText = string.Empty; // TODO: Initialize to an appropriate value
     SshCommand target = new SshCommand(session, commandText); // TODO: Initialize to an appropriate value
     string commandText1 = string.Empty; // TODO: Initialize to an appropriate value
     AsyncCallback callback = null; // TODO: Initialize to an appropriate value
     object state = null; // TODO: Initialize to an appropriate value
     IAsyncResult expected = null; // TODO: Initialize to an appropriate value
     IAsyncResult actual;
     actual = target.BeginExecute(commandText1, callback, state);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
        private void Arrange()
        {
            var random = new Random();

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelSessionMock = new Mock<IChannelSession>(MockBehavior.Strict);
            _commandText = random.Next().ToString(CultureInfo.InvariantCulture);
            _encoding = Encoding.UTF8;

            var seq = new MockSequence();
            _sessionMock.InSequence(seq).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object);
            _channelSessionMock.InSequence(seq).Setup(p => p.Open());
            _channelSessionMock.InSequence(seq).Setup(p => p.SendExecRequest(_commandText)).Returns(true);

            _sshCommand = new SshCommand(_sessionMock.Object, _commandText, _encoding);
            _sshCommand.BeginExecute();
        }
コード例 #7
0
        private void Arrange()
        {
            var random = new Random();

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelSessionMock = new Mock<IChannelSession>(MockBehavior.Strict);
            _commandText = random.Next().ToString(CultureInfo.InvariantCulture);
            _encoding = Encoding.UTF8;
            _expectedExitStatus = random.Next();
            _dataA = random.Next().ToString(CultureInfo.InvariantCulture);
            _dataB = random.Next().ToString(CultureInfo.InvariantCulture);
            _extendedDataA = random.Next().ToString(CultureInfo.InvariantCulture);
            _extendedDataB = random.Next().ToString(CultureInfo.InvariantCulture);
            _asyncResult = null;

            var seq = new MockSequence();
            _sessionMock.InSequence(seq).Setup(p => p.CreateChannelSession()).Returns(_channelSessionMock.Object);
            _channelSessionMock.InSequence(seq).Setup(p => p.Open());
            _channelSessionMock.InSequence(seq).Setup(p => p.SendExecRequest(_commandText))
                .Returns(true)
                .Raises(c => c.Closed += null, new ChannelEventArgs(5));
            _channelSessionMock.InSequence(seq).Setup(p => p.IsOpen).Returns(true);
            _channelSessionMock.InSequence(seq).Setup(p => p.Close());
            _channelSessionMock.InSequence(seq).Setup(p => p.Dispose());

            _sshCommand = new SshCommand(_sessionMock.Object, _commandText, _encoding);
            _asyncResult = _sshCommand.BeginExecute();

            _channelSessionMock.Raise(c => c.DataReceived += null,
                new ChannelDataEventArgs(0, _encoding.GetBytes(_dataA)));
            _channelSessionMock.Raise(c => c.ExtendedDataReceived += null,
                new ChannelExtendedDataEventArgs(0, _encoding.GetBytes(_extendedDataA), 0));
            _channelSessionMock.Raise(c => c.DataReceived += null,
                new ChannelDataEventArgs(0, _encoding.GetBytes(_dataB)));
            _channelSessionMock.Raise(c => c.ExtendedDataReceived += null,
                new ChannelExtendedDataEventArgs(0, _encoding.GetBytes(_extendedDataB), 0));
            _channelSessionMock.Raise(c => c.RequestReceived += null,
                new ChannelRequestEventArgs(new ExitStatusRequestInfo((uint) _expectedExitStatus)));
        }
コード例 #8
0
        public override bool Execute(string command, string arguments, out ProcessExecuteStatus process_status, out string process_output, out string process_error, Dictionary <string, string> env = null,
                                     Action <string> OutputDataReceived = null, Action <string> OutputErrorReceived = null, [CallerMemberName] string memberName = "", [CallerFilePath] string fileName = "", [CallerLineNumber] int lineNumber = 0)
        {
            CallerInformation caller = new CallerInformation(memberName, fileName, lineNumber);

            if (!this.IsConnected)
            {
                throw new InvalidOperationException("The SSH session is not connected.");
            }
            process_status = ProcessExecuteStatus.Unknown;
            process_output = "";
            process_error  = "";
            if (env != null && env.Count > 0)
            {
                StringBuilder vars = new StringBuilder();
                foreach (KeyValuePair <string, string> kv in env)
                {
                    vars.AppendFormat("{0}={1} ", kv.Key, kv.Value);
                }
                command = vars.ToString() + command;
            }
            SshCommand cmd = this.SshClient.CreateCommand(command + " " + arguments);

            Debug("Executing command {0} {1}.", command, arguments);
            Stopwatch cs = new Stopwatch();

            cs.Start();
            CommandAsyncResult result;

            try
            {
                result = cmd.BeginExecute(new AsyncCallback(SshCommandAsyncCallback), new KeyValuePair <SshCommand, Stopwatch>(cmd, cs)) as CommandAsyncResult;
                cmd.EndExecute(result);
            }
            catch (SshConnectionException sce)
            {
                Error(caller, sce, "SSH connection error attempting to execute {0} {1}.", command, arguments);
                return(false);
            }
            catch (SshOperationTimeoutException te)
            {
                Error(caller, te, "SSH connection timeout attempting to execute {0} {1}.", command, arguments);
                return(false);
            }
            catch (SshException se)
            {
                Error(caller, se, "SSH error attempting to execute {0} {1}.", command, arguments);
                return(false);
            }
            catch (Exception e)
            {
                Error(caller, e, "Error attempting to execute over SSH {0} {1}.", command, arguments);
                return(false);
            }
            KeyValuePair <SshCommand, Stopwatch> s = (KeyValuePair <SshCommand, Stopwatch>)result.AsyncState;

            process_output = s.Key.Result.Trim();
            process_error  = s.Key.Error.Trim();
            if (s.Value.IsRunning)
            {
                s.Value.Stop();
            }
            process_output = cmd.Result.Trim();
            process_error  = process_output + cmd.Error.Trim();
            if (cmd.ExitStatus == 0)
            {
                Debug(caller, "Execute {0} returned zero exit code. Output: {1}.", command + " " + arguments, process_output);
                process_status = ProcessExecuteStatus.Completed;
                cmd.Dispose();
                return(true);
            }
            else
            {
                process_status = ProcessExecuteStatus.Error;
                Debug(caller, "Execute {0} returned non-zero exit code {2}. Error: {1}.", command + " " + arguments, process_error, cmd.ExitStatus);
                cmd.Dispose();
                return(false);
            }
        }
コード例 #9
0
ファイル: SftpStorage.cs プロジェクト: xmxth001/SmartSync
        public override IEnumerable <Directory> GetAllDirectories(string[] exclusions = null)
        {
            Initialize();

            if (SshClient == null)
            {
                foreach (Directory directory in base.GetAllDirectories(exclusions))
                {
                    yield return(directory);
                }

                yield break;
            }

            SshCommand command = SshClient.RunCommand("ls -alR --time-style=full-iso " + Path);

            if (command.ExitStatus < 0)
            {
                foreach (Directory directory in base.GetAllDirectories(exclusions))
                {
                    yield return(directory);
                }

                yield break;
            }

            // Command output looks like this block
            //   /data/web/julien/www/Content:
            //   total 12
            //   drwxr-xr-x 3 pi pi 4096 2016-11-01 17:01:38.064671398 +0100 .
            //   drwxr-xr-x 9 pi pi 4096 2016-11-01 17:03:46.933370227 +0100 ..
            //   drwxr-xr-x 2 pi pi 4096 2016-11-01 17:01:54.284507630 +0100 Articles
            //
            //   /data/web/julien/www/Content/Articles:
            //   total 72
            //   drwxr-xr-x 2 pi pi  4096 2016-11-01 17:01:54.284507630 +0100 .
            //   drwxr-xr-x 3 pi pi  4096 2016-11-01 17:01:38.064671398 +0100 ..
            //   -rw-r--r-- 1 pi pi 13414 2016-10-23 19:27:41.000000000 +0200 c-sharp-utilisation-linq.md
            //   -rw-r--r-- 1 pi pi 21944 2016-10-23 19:28:37.000000000 +0200 interoperabilite-systemes.md
            //   -rw-r--r-- 1 pi pi 11665 2016-10-27 22:38:12.000000000 +0200 securite-les-injections-sql.md
            //   -rw-r--r-- 1 pi pi  8651 2016-10-23 19:28:04.000000000 +0200 unification-contenu-fournisseur.md

            List <Directory> result = new List <Directory>();

            using (System.IO.StringReader reader = new System.IO.StringReader(command.Result))
            {
                Dictionary <string, SftpCachedDirectory> directories = new Dictionary <string, SftpCachedDirectory>();

                while (true)
                {
                    string line = reader.ReadLine();
                    if (line == null)
                    {
                        break;
                    }
                    if (!line.EndsWith(":"))
                    {
                        continue;
                    }

                    string path = Combine(Path, line.Remove(line.Length - 1));
                    string name = System.IO.Path.GetFileName(path);
                    SftpCachedDirectory directory;

                    // Root directory
                    if (path == Path)
                    {
                        directory = new SftpCachedDirectory(this, null, path, name);
                        directories.Add(path, directory);

                        PopulateFiles(directory, reader);
                        yield return(directory);

                        continue;
                    }

                    // Children directories
                    string parentPath          = Combine(path, "..");
                    SftpCachedDirectory parent = directories[parentPath];

                    directory = new SftpCachedDirectory(this, parent, path, name);
                    directories.Add(path, directory);
                    parent.directories.Add(directory);

                    path = directory.Path + "/";
                    if (exclusions != null && exclusions.Any(e => MatchPattern(path, e)))
                    {
                        continue;
                    }

                    PopulateFiles(directory, reader);
                    yield return(directory);
                }
            }
        }
コード例 #10
0
ファイル: SshExtensions.cs プロジェクト: OneDR/Hermes
        internal static async Task <SshCommand> RunCommandAsync(this SshClient client, string strCommand)
        {
            SshCommand command = await Task.Run(() => client.RunCommand(strCommand));

            return(command);
        }
コード例 #11
0
        /// <summary>
        /// Handle Falcom commands. Determine if command is valid,
        /// what is the type of it, and execute (if valid).
        /// </summary>
        /// <param name="input">Falcon command (including cmd char)</param>
        /// <param name="output">Execution result</param>
        /// <returns>Is command valid, Command message, Command Type, On or Off flag</returns>
        public static bool Parse(string cmd, ref string message, ref Command.Type type, ref Argument argumentObj)
        {
            // extract command name and arguments
            string[] cmdArr  = cmd.Split(CMD_SPLITTER);
            string   cmdName = cmdArr[CMD_NAME_INDX];


            bool noArgument = (cmdArr.Length <= 1) ? true : false;

            SshCommand     sshCmd     = new SshCommand();
            PingCommand    pingCmd    = new PingCommand();
            ClearCommand   clearCmd   = new ClearCommand();
            HelpCommand    helpCmd    = new HelpCommand();
            InvalidCommand invalidCmd = new InvalidCommand();

            // return values to caller according to cmd name
            switch (cmdName)
            {
            case "ssh":

                if (noArgument)
                {
                    message = sshCmd.GetNoArgumentMsg();
                    return(false);
                }

                if (cmdArr.Length < 4)
                {
                    message = sshCmd.GetInvalidArgumentMsg();
                    return(false);
                }

                string sshArgs = cmdArr[CMD_ARG_INDX] + " " +
                                 cmdArr[CMD_ARG_INDX + 1] + " " +
                                 cmdArr[CMD_ARG_INDX + 2];

                sshCmd.InitArgument(sshArgs);
                type = sshCmd.GetCommandType();

                if (!sshCmd.IsValidArgument())
                {
                    message = sshCmd.GetInvalidArgumentMsg();
                    return(false);
                }
                argumentObj = sshCmd.GetArgumentObject();
                return(true);

            case "ping":

                if (noArgument)
                {
                    message = pingCmd.GetNoArgumentMsg();
                    return(false);
                }

                pingCmd.InitArgument(cmdArr[CMD_ARG_INDX]);
                type = pingCmd.GetCommandType();

                argumentObj = pingCmd.GetArgumentObject();
                message     = pingCmd.GetSuccessMsg();
                return(true);

            case "clear":
                type    = clearCmd.GetCommandType();
                message = clearCmd.GetSuccessMsg();
                return(true);

            case "help":
                if (noArgument)
                {
                    message = helpCmd.GetNoArgumentMsg();
                    return(false);
                }
                helpCmd.InitArgument(cmdArr[CMD_ARG_INDX]);
                if (!helpCmd.IsValidArgument())
                {
                    message = helpCmd.GetInvalidArgumentMsg();
                    return(false);
                }

                switch (cmdArr[CMD_ARG_INDX])
                {
                case "ssh":
                    message = sshCmd.GetHelpMsg();
                    break;

                case "ping":
                    message = pingCmd.GetHelpMsg();
                    break;

                case "clear":
                    message = clearCmd.GetHelpMsg();
                    break;

                case "help":
                    message = helpCmd.GetHelpMsg();
                    break;
                }
                break;

            default:
            {
                invalidCmd.InitArgument(cmd);
                type    = invalidCmd.GetCommandType();
                message = invalidCmd.GetInvalidArgumentMsg();
                break;
            }
            }
            return(false);
        }
コード例 #12
0
 protected void ValidateError(SshCommand res, GameResult result)
 {
     result.Succes       = false;
     result.ErrorMessage = EscapeUtf8(res.Error);
 }
コード例 #13
0
 public Task <string> RunCommandAsync(SshCommand cmd, CancellationToken token)
 {
     throw new NotImplementedException();
 }
コード例 #14
0
        public void Post([FromBody] string value)
        {
            string _host     = "172.16.62.56";
            string _username = "******";
            string _password = "******";
            int    _port     = 22;

            try
            {
                ConnectionInfo conInfo = new ConnectionInfo(_host, _port, _username, new AuthenticationMethod[] {
                    new PasswordAuthenticationMethod(_username, _password)
                });
                dynamic JSONData    = JsonConvert.DeserializeObject(value);
                string  AdminAction = JSONData["Action"];
                if (AdminAction == "Lock")
                {
                    List <string> IPList = JsonConvert.DeserializeObject <List <string> >((string)JSONData["IP"]);
                    using (FlowDatas db = new FlowDatas())
                    {
                        List <string> DbLockIPs = db.LockUsers.Select(c => c.IP)
                                                  .Union(db.WhiteUsers.Select(c => c.IP)).ToList();
                        List <string> LockIP = IPList.Where(c => !DbLockIPs.Contains(c)).ToList();

                        using (SshClient sshClient = new SshClient(conInfo))
                        {
                            if (!sshClient.IsConnected)
                            {
                                //連線
                                sshClient.Connect();
                            }

                            foreach (var q in LockIP)
                            {
                                SshCommand sshCmd = sshClient.RunCommand("ip firewall address-list add address=" + q + " list=lockip");
                                if (!string.IsNullOrWhiteSpace(sshCmd.Error))
                                {
                                    Debug.WriteLine(sshCmd.Error);
                                }
                                else
                                {
                                    db.LockUsers.Add(new FlowDatas.LockTable {
                                        Id = Guid.NewGuid(), IP = q, Time = DateTime.Now, Reason = "惡意行為"
                                    });
                                    Debug.WriteLine(sshCmd.Result);
                                }
                            }
                            if (LockIP.Count > 0)
                            {
                                db.SaveChanges();
                            }
                        }
                    }
                }
                else if (AdminAction == "UnLock")
                {
                    string IP = (string)JSONData["IP"];

                    using (FlowDatas db = new FlowDatas())
                        if (db.LockUsers.Where(c => c.IP == IP).Count() > 0)
                        {
                            using (SshClient sshClient = new SshClient(conInfo))
                            {
                                if (!sshClient.IsConnected)
                                {
                                    //連線
                                    sshClient.Connect();
                                }


                                SshCommand sshCmd = sshClient.RunCommand("/ip firewall address-list remove [find list=lockip  address =" + IP + "]");
                                if (!string.IsNullOrWhiteSpace(sshCmd.Error))
                                {
                                    Debug.WriteLine(sshCmd.Error);
                                }
                                else
                                {
                                    db.LockUsers.RemoveRange(db.LockUsers.Where(c => c.IP == IP).ToArray());
                                    db.SaveChanges();
                                    Debug.WriteLine(sshCmd.Result);
                                }
                            }
                        }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        }
コード例 #15
0
ファイル: Program.cs プロジェクト: 1337g/sshiva
        static void Main(string[] args)
        {
            string        key      = "";
            string        user     = "******";
            string        password = "";
            string        command  = "";
            bool          keyAuth  = false;
            List <string> hosts    = new List <string>();

            foreach (string arg in args)
            {
                switch (arg.Split('=')[0])
                {
                case "/user":
                    user = arg.Split('=')[1];
                    break;

                case "/key":
                    key     = arg.Split('=')[1];
                    keyAuth = true;
                    break;

                case "/password":
                    password = arg.Split('=')[1];
                    break;

                case "/hosts":
                    hosts = arg.Split('=')[1].Split(',').ToList <string>();
                    break;

                case "/command":
                    command = arg.Split('=')[1];
                    break;
                }
            }
            try
            {
                ConnectionInfo connectionInfo;
                if (!(String.IsNullOrEmpty(key) && String.IsNullOrEmpty(password)) && hosts.Count > 0 && !String.IsNullOrEmpty(command))
                {
                    if (keyAuth)
                    {
                        foreach (string host in hosts)
                        {
                            Console.WriteLine($"Running {command} on {host}");
                            connectionInfo = new ConnectionInfo(host, user, new PrivateKeyAuthenticationMethod(key));
                            SshClient sshclient = new SshClient(connectionInfo);
                            sshclient.Connect();
                            SshCommand sc = sshclient.CreateCommand(command);
                            sc.Execute();
                            if (sc.ExitStatus != 0)
                            {
                                Console.WriteLine("Error in Command: ");
                                Console.WriteLine("Error: {0}", sc.Error);
                                Console.WriteLine("Exit Status: {0}", sc.ExitStatus);
                            }
                            else
                            {
                                Console.WriteLine(sc.Result);
                            }
                        }
                    }
                    else
                    {
                        foreach (string host in hosts)
                        {
                            Console.WriteLine($"Running {command} on {host}");
                            connectionInfo = new ConnectionInfo(host, user, new PasswordAuthenticationMethod(user, password));
                            SshClient sshclient = new SshClient(connectionInfo);
                            sshclient.Connect();
                            SshCommand sc = sshclient.CreateCommand(command);
                            sc.Execute();
                            if (sc.ExitStatus != 0)
                            {
                                Console.WriteLine("Error in Command: ");
                                Console.WriteLine("Error: {0}", sc.Error);
                                Console.WriteLine("Exit Status: {0}", sc.ExitStatus);
                            }
                            else
                            {
                                Console.WriteLine(sc.Result);
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("usage sshiva.exe /user=root /host=localhost /password=P@ssw0rd /command=\"whoami\"");
                    Console.ReadKey();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
コード例 #16
0
        /// <summary>
        /// Executes a synchronous command
        /// </summary>
        /// <param name="result">The result object for the current operation</param>
        /// <param name="command">The definition of the command to execute</param>
        /// <param name="sshCommand">The SSH command object to execute</param>
        private static void ExecuteSyncCommand(OperationResult result, SyncCommand command, SshCommand sshCommand)
        {
            sshCommand.Execute();
            Logger.WriteLine("Command returned exit code {0}", sshCommand.ExitStatus.ToString());
            Logger.WriteRaw(sshCommand.Result, LogLevel.Debug);

            if (!command.SuccessCodes.Contains(sshCommand.ExitStatus))
            {
                if (!string.IsNullOrWhiteSpace(sshCommand.Error))
                {
                    throw new Microsoft.MetadirectoryServices.ExtensibleExtensionException(sshCommand.Error);
                }
                else
                {
                    throw new Microsoft.MetadirectoryServices.ExtensibleExtensionException("The command returned an exit code that was not in the list of successful exit codes: " + sshCommand.ExitStatus.ToString());
                }
            }

            if (command.HasObjects)
            {
                result.ExecutedCommandsWithObjects.Add(sshCommand);
            }

            result.ExecutedCommands.Add(sshCommand);
        }
コード例 #17
0
        private void SendSSHCommand_Callback(object state)
        {
            _startSendCommandWaitHandle.WaitOne();

            var args = state as object[];

            int    i         = (int)args[0];
            int    size      = (int)args[1];
            string ipOrHost  = args[2].ToString();
            int    port      = (int)args[3];
            string user      = args[4].ToString();
            var    pkf       = args[5] as PrivateKeyFile;
            string password  = args[6].ToString();
            string command   = args[7].ToString();
            var    timeout   = TimeSpan.FromSeconds((int)args[8]);
            bool   keepAlive = (bool)args[9];

            //Try 2 times
            for (int t = 1; ; t++)
            {
                SshClient client = null;
                try {
                    _clients.TryGetValue(ipOrHost, out client);

                    if (client == null)
                    {
                        client = pkf == null ? new SshClient(ipOrHost, port, user, password) : new SshClient(ipOrHost, port, user, pkf);
                    }
                    client.ConnectionInfo.Timeout = timeout;

                    if (!_cancellationTokenSource.Token.IsCancellationRequested)
                    {
                        if (!client.IsConnected)
                        {
                            client.Connect();
                        }
                        if (!client.IsConnected)
                        {
                            throw new Exception("Failed to connect");
                        }
                    }

                    if (!_cancellationTokenSource.Token.IsCancellationRequested)
                    {
                        SshCommand sshc = client.CreateCommand(command);
                        sshc.CommandTimeout = timeout;

                        string result = sshc.Execute();

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            result = "OK";
                        }

                        _synchronizationContext.Send((state2) => { Log(state2.ToString()); }, "  " + i + " / " + size + " - " + ipOrHost + "\t- " + result);

                        if (keepAlive)
                        {
                            _clients.TryAdd(ipOrHost, client);
                        }
                        else
                        {
                            DisposeAndForgetSshClient(ipOrHost, client);
                        }
                    }
                    break;
                }
                catch (Exception ex) {
                    if (_cancellationTokenSource.IsCancellationRequested)
                    {
                        break;
                    }
                    else
                    {
                        if (t == 2) //Try 2 times
                        {
                            _synchronizationContext.Post((state2) => { Log(state2.ToString()); }, "  " + i + " / " + size + " - " + ipOrHost + "\t- " + ex.Message.Replace("\n", " ").Replace("\r", " ").Replace("\t", " "));
                        }
                        else
                        {
                            DisposeAndForgetSshClient(ipOrHost, client);
                        }
                    }
                }
            }

            if (Interlocked.Increment(ref _commandsSend) >= _ipsAndHosts.Length)
            {
                _synchronizationContext.Post((state2) => {
                    btnSSHCommand.Enabled    = true;
                    btnSSHCommand.Text       = "SSH command:";
                    nudTimeout.Enabled       = chkKeepAlive.Enabled = true;
                    _cancellationTokenSource = new CancellationTokenSource();

                    Log("\nv-----          Done          -----v @ " + DateTime.Now.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ss") + "\n");
                }, null);
            }
        }
コード例 #18
0
 void ExecuteAsyncCommand(SshClient client, string action, AsyncCallback callBack, SshCommand command)
 {
     command = client.CreateCommand(String.Format(UNIX_COMMAND_FORMAT, _serviceName, action), UTF8Encoding.UTF8);
     command.BeginExecute(String.Format(UNIX_COMMAND_FORMAT, _serviceName, action), callBack, null);
 }
コード例 #19
0
        string ExecuteSyncCommand(SshClient client, string action)
        {
            SshCommand command = client.CreateCommand(String.Format(UNIX_COMMAND_FORMAT, _serviceName, action, username, password));

            return(command.Execute());
        }
コード例 #20
0
    public void Run()
    {
        string host     = "10.1.5.110";
        int    port     = 2222;
        string username = "******";
        string password = "******";
        string rsaKey   = "C:/Users/FengZeng/.ssh/id_rsa.pub";

        var connectionInfo = new ConnectionInfo(host, port,
                                                username,
                                                new PasswordAuthenticationMethod(username, password),
                                                new PrivateKeyAuthenticationMethod(rsaKey));

        using (var client = new SshClient(connectionInfo))
        {
            client.Connect();
            Console.WriteLine("IsConnected:" + client.IsConnected);

            SshCommand cmd = client.RunCommand("h");
            Console.WriteLine("cmd:" + cmd.Result);
        }

        //    using (var sshClient = new SshClient(host, port, username, password))

        //    {
        //        byte[] expectedFingerPrint = new byte[] {
        //                                        0x66, 0x31, 0xaf, 0x00, 0x54, 0xb9, 0x87, 0x31,
        //                                        0xff, 0x58, 0x1c, 0x31, 0xb1, 0xa2, 0x4c, 0x6b
        //                                    };

        //        sshClient.HostKeyReceived += (sender, e) =>
        //        {
        //            if (expectedFingerPrint.Length == e.FingerPrint.Length)
        //            {
        //                for (var i = 0; i < expectedFingerPrint.Length; i++)
        //                {
        //                    if (expectedFingerPrint[i] != e.FingerPrint[i])
        //                    {
        //                        //e.CanTrust = false;
        //                        //break;
        //                    }
        //                }
        //            }
        //            else
        //            {
        //                //e.CanTrust = false;
        //            }


        //            using (var cmd = sshClient.CreateCommand("1s"))
        //            {
        //                var res = cmd.Execute();
        //                Console.WriteLine(res);
        //            }
        //        };
        //        sshClient.Connect();

        //        //using (var cmd = sshClient.CreateCommand("1s"))
        //        //{
        //        //    var res = cmd.Execute();
        //        //    Console.WriteLine(res);
        //        //}
        //    }
    }
コード例 #21
0
        private static string runCommand(string command, SshClient client)
        {
            SshCommand sshCommand = client.RunCommand(command);

            return(sshCommand.Result.Trim());
        }
コード例 #22
0
ファイル: SshCommandTest.cs プロジェクト: delfinof/ssh.net
 [Ignore] // placeholder for actual test
 public void ExecuteTest1()
 {
     Session session = null; // TODO: Initialize to an appropriate value
     string commandText = string.Empty; // TODO: Initialize to an appropriate value
     var encoding = Encoding.UTF8;
     SshCommand target = new SshCommand(session, commandText, encoding); // TODO: Initialize to an appropriate value
     string commandText1 = string.Empty; // TODO: Initialize to an appropriate value
     string expected = string.Empty; // TODO: Initialize to an appropriate value
     string actual;
     actual = target.Execute(commandText1);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
コード例 #23
0
        public async static Task <List <Diskinfo> > GetConsoleInfo()
        {
            var RGHSett = RGHSettings.ProgramSetting.SelectedFtpSetting;

            return(await Task.Run(() =>
            {
                try
                {
                    using (var client = new SshClient(RGHSett.FtpHost, RGHSett.FtpUserName, RGHSett.FtpPassword))
                    {
                        client.Connect();

                        //head -n1 /etc/issue Show distri­bution
                        //date
                        //uptime
                        //uname -a
                        //cat /proc/cpuinfo

                        var list = new List <string>()
                        {
                            "KNAME", "SIZE", "TYPE", "MOUNTPOINT"
                        };
                        var resultList = new Dictionary <string, List <string> >();
                        foreach (var name in list)
                        {
                            SshCommand sc = client.CreateCommand($"lsblk --all -b --output {name}");
                            sc.Execute();
                            resultList.Add(name,
                                           sc.Result.Split(new[] { "\r\n", "\r", "\n" },
                                                           StringSplitOptions.None).ToList());
                        }

                        string[] ol = { "", "", "", "", "", "", "", "", "", "" };

                        var listDiskInfo = new List <Diskinfo>();

                        for (int i = 1; i < resultList["KNAME"].Count; i++)
                        {
                            if (resultList["TYPE"][i] == "loop" || resultList["MOUNTPOINT"][i] == "")
                            {
                                continue;
                            }
                            var mpoint = resultList["MOUNTPOINT"][i];
                            var listfindmnt = new List <string>()
                            {
                                "SIZE", "USED", "USE%", "AVAIL", "FSTYPE", "LABEL"
                            };
                            //findmnt -T {mpoint} -o SIZE,USED,USE%,LABEL,AVAIL,FSTYPE -n
                            SshCommand sc2 = client.CreateCommand($"findmnt -T {mpoint} -o SIZE,USED,USE%,AVAIL,FSTYPE,LABEL -f -n");
                            sc2.Execute();
                            var dtInfo = sc2.Result.Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                            ol[0] = resultList["KNAME"][i];
                            ol[1] = resultList["SIZE"][i];
                            ol[2] = resultList["TYPE"][i];
                            ol[3] = string.Join("/", resultList["MOUNTPOINT"][i].Split('/').Reverse().Take(2).Reverse().ToList());
                            ol[4] = dtInfo[0];
                            ol[5] = dtInfo[1];
                            ol[6] = dtInfo[2];
                            ol[7] = dtInfo[3];
                            ol[8] = dtInfo[4];
                            ol[9] = dtInfo.Count() == 6 ? dtInfo[5] : "";
                            if (ol.All(s => string.IsNullOrWhiteSpace(s)))
                            {
                                continue;
                            }
                            listDiskInfo.Add(new Diskinfo(ol.ToList()));
                        }
                        return listDiskInfo;
                    }
                }
                catch (Exception ex)
                {
                    ErrorHandler.Error(ex);
                    return new List <Diskinfo>();
                }
            }));
        }
コード例 #24
0
        private void StartStream(SshClient client, string game) // zaženemo stream z izbrano igro
        {
            if (game.Contains(" "))
            {
                game = "'" + game + "'";
            }
            flowLayoutPanel1.Visible = false;
            infoLabel.Text           = "Zagon igre...\n" +
                                       "Za izhod iz pretakanja pritisnite: \n\n" +
                                       "Na PC-ju: ALT in F12 \n" +
                                       "Na Pi-ju: CTRL, ALT, SHIFT in Q";
            infoLabel.Visible = true;

            string optionalArgs = "";

            if (widthRes > 0)
            {
                optionalArgs += "-width " + widthRes + " ";
            }
            if (heightRes > 0)
            {
                optionalArgs += "-height " + heightRes + " ";
            }
            if (bitrate > 0)
            {
                optionalArgs += "-bitrate " + bitrate + " ";
            }
            if (packetsize > 0)
            {
                optionalArgs += "-packetsize " + packetsize + " ";
            }
            if (codec != "auto")
            {
                optionalArgs += "-codec " + codec + " ";
            }
            if (remote == true)
            {
                optionalArgs += "-remote ";
            }
            if (nosops == false)
            {
                optionalArgs += "-nosops ";
            }
            if (localAudio == true)
            {
                optionalArgs += "-localaudio ";
            }
            if (sorround == true)
            {
                optionalArgs += "-sorround ";
            }
            if (platform != "auto")
            {
                optionalArgs += "-platform " + platform + " ";
            }

            streamCommand = client.CreateCommand
                                ("moonlight stream -" + resolution + " -fps " + fps + " -app " + game + " " + optionalArgs);

            streamWorker                     = new BackgroundWorker();
            streamWorker.DoWork             += BeginStream;
            streamWorker.RunWorkerCompleted += UpdateGUI;
            streamWorker.RunWorkerAsync();
        }
コード例 #25
0
 public void EndTaskExecute(IAsyncResult iar, SshCommand cmd)
 {
     cmd.EndExecute(iar);
 }
コード例 #26
0
        public bool Execute(RemoteTask[] tasks, RemoteInput[] inputs, RemoteResult[] results)
        {
            if (this._sshClient == null)
            {
                return(false);
            }

            string path = this._remotePath + this._workspaceName + "/solver-" + this._solverNumber + "/";

            #region Working directory reset

            using (SshCommand command = this._sshClient.CreateCommand("rm -rf " + path + "; mkdir -p " + path))
            {
                command.Execute();

                if (command.ExitStatus != 0)
                {
                    return(false);
                }
            }

            #endregion

            #region Input data upload

            if (inputs != null)
            {
                foreach (RemoteInput el in inputs)
                {
                    if (!el.Send(path, this._sshClient, this._sftpClient))
                    {
                        return(false);
                    }
                }
            }

            #endregion

            #region Tasks execution

            if (tasks != null)
            {
                foreach (RemoteTask el in tasks)
                {
                    if (!el.Execute(path, this._sshClient))
                    {
                        return(false);
                    }
                }
            }

            #endregion

            #region Output data download

            if (results != null)
            {
                foreach (RemoteResult el in results)
                {
                    if (!el.Receive(path, this._sshClient, this._sftpClient))
                    {
                        return(false);
                    }
                }
            }

            #endregion

            return(true);
        }
コード例 #27
0
ファイル: SshCommandTest.cs プロジェクト: pecegit/sshnet
 public void EndExecuteTest()
 {
     Session session = null; // TODO: Initialize to an appropriate value
     string commandText = string.Empty; // TODO: Initialize to an appropriate value
     SshCommand target = new SshCommand(session, commandText); // TODO: Initialize to an appropriate value
     IAsyncResult asyncResult = null; // TODO: Initialize to an appropriate value
     string expected = string.Empty; // TODO: Initialize to an appropriate value
     string actual;
     actual = target.EndExecute(asyncResult);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
コード例 #28
0
        private void runButton_Click(object sender, EventArgs e)
        {
            SshCommand executed = client.RunCommand(runSshTextBox.Text);

            outputTextBox.Text += Environment.NewLine + executed.Result.Replace("\n", Environment.NewLine);
        }
コード例 #29
0
ファイル: SshCommandTest.cs プロジェクト: pecegit/sshnet
 public void ErrorTest()
 {
     Session session = null; // TODO: Initialize to an appropriate value
     string commandText = string.Empty; // TODO: Initialize to an appropriate value
     SshCommand target = new SshCommand(session, commandText); // TODO: Initialize to an appropriate value
     string actual;
     actual = target.Error;
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
        public async Task <bool> ConfigureMachine(Machine machine)//TODO: Unifinished due to unknown elements related to lack of access to images on open nebula
        {
            //Construct configuration string
            List <MachineConfigurationUser> configurationUsers = new();
            var assignments = await GetContext().MachineAssignments.Where(ass => ass.MachineID == machine.MachineID).ToListAsync();

            foreach (var assignment in assignments)//TODO: Expecting issues with resolution of virtual properties on the items from the database
            {
                if (assignment.GroupID == null)
                {
                    if (await GetContext().Users.FindAsync(assignment.UserUsername) == null)
                    {
                        GetContext().Users.Add(await UserFactory.Create(assignment.UserUsername));
                    }
                    MachineConfigurationUser machineConfigurationUser = new();
                    machineConfigurationUser.Groups       = machine.LinuxGroups;
                    machineConfigurationUser.Username     = assignment.UserUsername;
                    machineConfigurationUser.UserPassword = assignment.OneTimePassword;



                    User user = (await GetContext().Users.FindAsync(assignment.UserUsername));
                    machineConfigurationUser.UserPublicKey = user.UserPublicKey;
                    configurationUsers.Add(machineConfigurationUser);
                }
                else
                {
                    foreach (var groupAssignment in GetContext().GroupAssignments.Where(ga => ga.GroupID == assignment.GroupID))
                    {
                        MachineConfigurationUser machineConfigurationUser = new();
                        machineConfigurationUser.Groups        = machine.LinuxGroups;
                        machineConfigurationUser.Username      = groupAssignment.User.Username;
                        machineConfigurationUser.UserPassword  = assignment.OneTimePassword;
                        machineConfigurationUser.UserPublicKey = groupAssignment.User.UserPublicKey;
                        configurationUsers.Add(machineConfigurationUser);
                    }
                }
            }
            var connectionInfo = new ConnectionInfo(machine.MachineStatus.MachineIp, _defaultUsername, new PrivateKeyAuthenticationMethod("admin", new PrivateKeyFile($"{SERVER_SCALABLE_TEACHING_PATH}/.ssh/id_rsa")));

            Console.WriteLine($"Connection info, ip: {machine.MachineStatus.MachineIp}, Default username: {_defaultUsername}, ");
            using (var client = new SshClient(connectionInfo))
            {
                MemoryStream stdin  = new();
                MemoryStream stdout = new();
                MemoryStream extout = new();
                client.Connect();

                //Add groups
                foreach (var group in machine.LinuxGroups)
                {
                    var command = client.CreateCommand($"sudo groupadd {group}");
                    var result  = command.BeginExecute();
                    await Task.Run(() => result.AsyncWaitHandle.WaitOne());
                }
                //Add users
                foreach (MachineConfigurationUser user in configurationUsers)
                {
                    var p = new Process();
                    p.StartInfo.UseShellExecute        = false;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.FileName  = "openssl";
                    p.StartInfo.Arguments = $"passwd -6 -salt {RandomString(10)} {user.UserPassword}";
                    p.Start();
                    await p.WaitForExitAsync();

                    string output = (await p.StandardOutput.ReadToEndAsync()).Trim();
                    Console.WriteLine($"Add user: {user.Username} hashed pw: {output}");


                    //Create User
                    var useraddCommand = await PerformSSHCommand(client, $"sudo useradd -s \"/usr/bin/bash\" -mp {output} {user.Username.ToLower()}");

                    Console.WriteLine($"MachineConfigurator: useraddCommand text: {useraddCommand.CommandText} Result: {useraddCommand.Result}");

                    //Add user to linux groups
                    foreach (var group in user.Groups)
                    {
                        var usermodCommand = await PerformSSHCommand(client, $"sudo usermod -aG {group} {user.Username.ToLower()}");

                        Console.WriteLine($"MachineConfigurator: usermodCommand text: {usermodCommand.CommandText} .Result {usermodCommand.Result}");
                    }

                    //Prep authorized_keys
                    var AuthorizedKeysCommand = await PerformSSHCommand(client, $"sudo mkdir -p /home/{user.Username.ToLower()}/.ssh &&" +
                                                                        $" sudo touch /home/{user.Username.ToLower()}/.ssh/authorized_keys &&" +
                                                                        $" sudo chown -R {user.Username.ToLower()}:{user.Username.ToLower()} /home/{user.Username.ToLower()}/.ssh &&" +
                                                                        $" sudo chmod -R 755 /home/{user.Username.ToLower()}/.ssh");

                    Console.WriteLine($"MachineConfigurator: AuthorizedKeysCommand text: {AuthorizedKeysCommand.CommandText} .Result {AuthorizedKeysCommand.Result}");

                    //Add key
                    var addKeyCommand = client.CreateCommand($"sudo sh -c 'echo \"{user.UserPublicKey}\" >> /home/{user.Username.ToLower()}/.ssh/authorized_keys'");
                    var addKeyResult  = addKeyCommand.BeginExecute();
                    await Task.Run(() => addKeyResult.AsyncWaitHandle.WaitOne());

                    Console.WriteLine($"MachineConfigurator: addKeyCommand text {addKeyCommand.CommandText} .Result {addKeyCommand.Result}");

                    //Remove password requirement from sudo
                    var nopasswdCommand = await PerformSSHCommand(client, $"sudo sh -c 'echo \"{user.Username.ToLower()} ALL=(ALL) NOPASSWD:ALL\" > /etc/sudoers.d/{user.Username.ToLower()}'");

                    Console.WriteLine($"MachineConfigurator: nopasswdCommand text {nopasswdCommand.CommandText} .Result {nopasswdCommand.Result}");
                }

                //Update
                var aptUpdateUpgradeCommand = await PerformSSHCommand(client, $"sudo apt-get update");

                Console.WriteLine($"MachineConfigurator: aptUpdateUpgradeCommand.Result {aptUpdateUpgradeCommand.Result}");

                //Prep for ppa
                var ppaPrepCommand = await PerformSSHCommand(client, $"sudo apt-get install -y software-properties-common");

                Console.WriteLine($"MachineConfigurator: ppaPrepCommand.Result {ppaPrepCommand.Result}");

                //PPA
                foreach (var ppa in machine.Ppa)
                {
                    var ppaAddCommand = await PerformSSHCommand(client, $"sudo add-apt-repository -y {ppa}");

                    Console.WriteLine($"MachineConfigurator: ppaAddCommand.Result {ppaAddCommand.Result}");
                }

                //Post ppa update and upgrade
                var postPpaUpdateCommand = await PerformSSHCommand(client, $"sudo apt-get update && sudo apt-get upgrade -y");

                Console.WriteLine($"MachineConfigurator: postPpaUpdateCommand.Result {postPpaUpdateCommand.Result}");

                //Install apts
                foreach (var apt in machine.Apt)
                {
                    var aptInstallCommand = await PerformSSHCommand(client, $"sudo apt-get install -y {apt}");

                    Console.WriteLine($"MachineConfigurator: aptInstallCommand.Result {aptInstallCommand.Result}");
                }

                //Apt cleanup
                SshCommand aptCleanupCommand = await PerformSSHCommand(client, $"sudo apt-get autoremove -y");

                Console.WriteLine($"MachineConfigurator: aptCleanupCommand.Result {aptCleanupCommand.Result}");

                client.Disconnect();
            }
            return(true); //TODO: Implement error handeling for configuration
        }
コード例 #31
0
 protected async override Task ExecuteAsync(CancellationToken stoppingToken)
 {
     while (!stoppingToken.IsCancellationRequested)
     {
         Console.WriteLine("Server Worker Çalıştırıldı!");
         IServer       _SServer = new SServer(new DbContext());
         List <Server> servers  = _SServer.GetServers();
         foreach (Server server in servers)
         {
             server.status_id = (int)enumStatus.Pasif;
             if (_SServer.UpdateServer(server))
             {
                 Console.WriteLine($"{server.server_name} Sunucusu Pasif Duruma Güncellendi!");
                 if (Debugger.IsAttached)
                 {
                     Thread.Sleep((int)TimeSpan.FromSeconds(10).TotalMilliseconds);
                 }
                 else
                 {
                     Thread.Sleep((int)TimeSpan.FromMinutes(10).TotalMilliseconds);
                 }
                 SshClient sshClient = null;
                 if (Debugger.IsAttached)
                 {
                     sshClient = new SshClient(server.local_ip, server.local_port, "root", "03102593");
                 }
                 else
                 {
                     sshClient = new SshClient(server.remote_ip, server.remote_port, "root", "031002593");
                 }
                 try
                 {
                     using (sshClient)
                     {
                         sshClient.Connect();
                         SshCommand lsCommand = sshClient.CreateCommand("ls");
                         lsCommand.Execute();
                         string        lsCommandResult = lsCommand.Result;
                         string[]      bufferArr       = lsCommandResult.Split('\n');
                         List <string> directories     = new List <string>(bufferArr);
                         directories.RemoveAll(x => String.IsNullOrEmpty(x));
                         foreach (string directory in directories)
                         {
                             SshCommand rmCommand = sshClient.CreateCommand($"rm -r {directory}");
                             rmCommand.Execute();
                         }
                         server.status_id = (int)enumStatus.Aktif;
                         if (_SServer.UpdateServer(server))
                         {
                             Console.WriteLine($"{server.server_name} Sunucusu Aktif Duruma Başarıyla Güncellendi!");
                         }
                         else
                         {
                             Console.WriteLine($"{server.server_name} Sunucusu Aktif Duruma Güncellenemedi!");
                         }
                     }
                 }
                 catch (Exception ex)
                 {
                     Console.WriteLine($"{ex.Message}");
                 }
             }
             else
             {
                 Console.WriteLine($"{server.server_name} Sunucusu Pasif Duruma Güncellenemedi!");
             }
         }
         if (Debugger.IsAttached)
         {
             await Task.Delay((int)TimeSpan.FromSeconds(30).TotalMilliseconds, stoppingToken);
         }
         else
         {
             await Task.Delay((int)TimeSpan.FromDays(1).TotalMilliseconds, stoppingToken);
         }
     }
 }
コード例 #32
0
ファイル: SSHClient.cs プロジェクト: wenfeifei/AntDeploy
        /// <summary>
        ///
        /// </summary>
        /// <param name="publishFolder">deploy文件目录</param>
        /// <param name="isrollBack"></param>
        /// <param name="isDefaultDockfile">上传的时候没有DockerFile要创建</param>
        public void DoDockerCommand(string publishFolder, bool isrollBack = false, bool isDefaultDockfile = false, string publishName = "publish")
        {
            string port        = string.Empty;
            string server_port = string.Empty;

            if (!publishFolder.EndsWith("/"))
            {
                publishFolder = publishFolder + "/";
            }
            //先查看本地是否有dockerFile
            var dockFilePath  = publishFolder + "Dockerfile";
            var dockFilePath2 = $"{(string.IsNullOrEmpty(publishName)?"": publishName+"/")}Dockerfile";
            // ReSharper disable once SimplifyConditionalTernaryExpression
            var isExistDockFile = isDefaultDockfile? false: _sftpClient.Exists(dockFilePath2);

            //如果本地存在dockerfile 那么就根据此创建image
            //如果不存在的话 就根据当前的netcore sdk的版本 进行创建相对应的 dockfile

            if (!isExistDockFile)
            {
                if (isrollBack)
                {
                    _logger($"dockerFile is not exist: {dockFilePath}", NLog.LogLevel.Error);
                    return;
                }


                if (!isDefaultDockfile)
                {
                    var createDockerFileResult = CreateDockerFile(dockFilePath);
                    if (!createDockerFileResult)
                    {
                        return;
                    }
                }
            }
            else
            {
                //如果项目中存在dockerFile 那么check 该DockerFile的Expose是否配置了 没有配置就报错
                try
                {
                    var dockerFileText = _sftpClient.ReadAllText(dockFilePath);
                    if (string.IsNullOrEmpty(dockerFileText))
                    {
                        _logger($"dockerFile is empty: {dockFilePath}", NLog.LogLevel.Error);
                        return;
                    }
                    var needAddPort = false;
                    var newPort     = string.Empty;
                    var newPortA    = dockerFileText.Split(new string[] { "EXPOSE " }, StringSplitOptions.None);
                    if (newPortA.Length != 2)
                    {
                        needAddPort = true;
                    }
                    else
                    {
                        if (!newPortA[0].EndsWith("#"))
                        {
                            foreach (var item in newPortA[1].Trim())
                            {
                                if (Char.IsDigit(item))
                                {
                                    newPort += item;
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }

                    if (string.IsNullOrEmpty(newPort))
                    {
                        needAddPort = true;
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(NetCorePort) && !this.ContainerPort.Equals(newPort))
                        {
                            _logger($"EXPOSE in dockerFile is defined,will use【{newPort}】replace【{ContainerPort}】", NLog.LogLevel.Warn);
                        }
                        else
                        {
                            _logger($"EXPOSE in dockerFile is : 【{newPort}】", NLog.LogLevel.Info);
                        }
                    }

                    //如果dockfile里面没有配置EXPOST 就用界面上提供的
                    port = needAddPort? ContainerPort:newPort;

                    var volumeInDockerFile = string.Empty;
                    var volumeExist        = dockerFileText.Split(new string[] { volumeProfix }, StringSplitOptions.None);
                    if (volumeExist.Length == 2)
                    {
                        var temp2 = volumeExist[1].Split('@');
                        if (temp2.Length > 0)
                        {
                            volumeInDockerFile = temp2[0];
                        }
                    }

                    if (!string.IsNullOrEmpty(volumeInDockerFile))
                    {
                        //dockerFIle里面有配置 volume
                        if (!string.IsNullOrEmpty(Volume) && !Volume.Equals(volumeInDockerFile))
                        {
                            _logger($"Volume in dockerFile is defined,will use【{volumeInDockerFile}】replace【{Volume}】", NLog.LogLevel.Warn);
                        }
                        else
                        {
                            _logger($"Volume in dockerFile is : 【{volumeInDockerFile}】", NLog.LogLevel.Info);
                        }

                        Volume = volumeInDockerFile;
                    }

                    var serverPostDockerFile      = string.Empty;
                    var serverPostDockerFileExist = dockerFileText.Split(new string[] { serverPortProfix }, StringSplitOptions.None);
                    if (serverPostDockerFileExist.Length == 2)
                    {
                        var temp2 = serverPostDockerFileExist[1].Split('@');
                        if (temp2.Length > 0)
                        {
                            serverPostDockerFile = temp2[0];
                        }
                    }

                    if (!string.IsNullOrEmpty(serverPostDockerFile))
                    {
                        //dockerFIle里面有配置 ServerPort
                        if (!string.IsNullOrEmpty(NetCorePort) && !ServerPort.Equals(serverPostDockerFile))
                        {
                            _logger($"ServerPort in dockerFile is defined,will use【{serverPostDockerFile}】replace【{ServerPort}】", NLog.LogLevel.Warn);
                        }
                        else
                        {
                            _logger($"ServerPort in dockerFile is : 【{serverPostDockerFile}】", NLog.LogLevel.Info);
                        }

                        server_port = serverPostDockerFile;
                    }
                    else
                    {
                        server_port = needAddPort ? ServerPort : port;
                    }

                    if (!string.IsNullOrEmpty(NetCoreEnvironment) || needAddPort)
                    {
                        var allLines        = _sftpClient.ReadAllLines(dockFilePath).ToList();
                        var entryPointIndex = 0;
                        var haveEnv         = false;
                        for (int i = 0; i < allLines.Count; i++)
                        {
                            var line = allLines[i];
                            if (line.Trim().StartsWith("ENTRYPOINT"))
                            {
                                entryPointIndex = i;
                            }

                            if (line.Trim().StartsWith("ENV ASPNETCORE_ENVIRONMENT"))
                            {
                                haveEnv = true;
                            }
                        }


                        if (entryPointIndex > 0)
                        {
                            var add = false;
                            if (needAddPort)
                            {
                                add = true;
                                allLines.Insert(entryPointIndex, "EXPOSE " + port);
                                _logger($"Add EXPOSE " + port + $" to dockerFile  : 【{dockFilePath}】", NLog.LogLevel.Info);
                            }

                            if (!haveEnv && !string.IsNullOrEmpty(NetCoreEnvironment))
                            {
                                add = true;
                                allLines.Insert(entryPointIndex, "ENV ASPNETCORE_ENVIRONMENT " + NetCoreEnvironment);
                                _logger($"Add ENV ASPNETCORE_ENVIRONMENT " + NetCoreEnvironment + $" to dockerFile  : 【{dockFilePath}】", NLog.LogLevel.Info);
                            }

                            if (add)
                            {
                                _sshClient.RunCommand($"set -e;cd ~;\\rm -rf \"{dockFilePath}\";");
                                //没有发现包含环境变量 就添加进去
                                using (var writer = _sftpClient.CreateText(dockFilePath))
                                {
                                    foreach (var line in allLines)
                                    {
                                        writer.WriteLine(line);
                                    }
                                    writer.Flush();
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger($"parse param in dockerFile fail: {dockFilePath},err:{ex.Message}", NLog.LogLevel.Error);
                    return;
                }
            }

            //执行docker build 生成一个镜像
            var dockerBuildResult = RunSheell($"docker build --no-cache --rm -t {PorjectName}:{ClientDateTimeFolderName} -f {dockFilePath} {publishFolder} ");

            if (!dockerBuildResult)
            {
                _logger($"build image fail", NLog.LogLevel.Error);
                return;
            }

            var continarName = "d_" + PorjectName;


            //先发送退出命令
            //https://stackoverflow.com/questions/40742192/how-to-do-gracefully-shutdown-on-dotnet-with-docker

            SshCommand r1 = null;

            try
            {
                r1 = _sshClient.RunCommand($"docker stop -t 10 {continarName}");
                if (r1.ExitStatus == 0)
                {
                    _logger($"docker stop -t 10 {continarName}", LogLevel.Info);
                }

                Thread.Sleep(5000);
            }
            catch (Exception)
            {
                //ignore
            }

            try
            {
                //查看容器有没有在runing 如果有就干掉它
                r1 = _sshClient.RunCommand($"docker rm -f {continarName}");
                if (r1.ExitStatus == 0)
                {
                    _logger($"docker rm -f {continarName}", LogLevel.Info);
                }
            }
            catch (Exception)
            {
                //ignore
            }


            if (string.IsNullOrEmpty(port))
            {
                port = ContainerPort;
            }

            if (string.IsNullOrEmpty(server_port))
            {
                server_port = ServerPort;
            }

            string volume = GetVolume();

            // 根据image启动一个容器
            var dockerRunRt = RunSheell($"docker run --name {continarName}{volume} -d --restart=always -p {server_port}:{port} {PorjectName}:{ClientDateTimeFolderName}");

            if (!dockerRunRt)
            {
                _logger($"docker run fail", NLog.LogLevel.Error);
                return;
            }

            //把旧的image给删除
            r1 = _sshClient.RunCommand("docker images --format '{{.Repository}}:{{.Tag}}:{{.ID}}' | grep '^" + PorjectName + ":'");
            if (r1.ExitStatus == 0 && !string.IsNullOrEmpty(r1.Result))
            {
                var deleteImageArr = r1.Result.Split('\n');
                var clearOldImages = false;
                foreach (var imageName in deleteImageArr)
                {
                    if (imageName.StartsWith($"{PorjectName}:{ClientDateTimeFolderName}:"))
                    {
                        //当前版本
                        continue;
                    }

                    var imageArr = imageName.Split(':');
                    if (imageArr.Length == 3)
                    {
                        var r2 = _sshClient.RunCommand($"docker rmi {imageArr[2]}");
                        if (r2.ExitStatus == 0)
                        {
                            if (!clearOldImages)
                            {
                                _logger($"start to clear old images of name:{PorjectName}", LogLevel.Info);
                                clearOldImages = true;
                            }
                            _logger($"docker rmi {imageArr[2]} [{imageName}]", LogLevel.Info);
                        }
                    }
                }
            }


            try
            {
                //查看是否有<none>的image 把它删掉 因为我们创建image的时候每次都会覆盖所以会产生一些没有的image
                _sshClient.RunCommand($"if docker images -f \"dangling=true\" | grep ago --quiet; then docker rmi -f $(docker images -f \"dangling=true\" -q); fi");
            }
            catch (Exception)
            {
                //igore
            }

            ClearOldHistroy();
        }
コード例 #33
0
        private static void RebuildPiWebsite()
        {
            // instantiate SSH client
            using (SshClient client = new SshClient(_config["pi:ip"], _config["pi:user"], _config["pi:password"]))
            {
                var cmds = new StringBuilder();

                BuildInfoEcho(cmds, "Navigating to ~/nodejs/LircNodeJsWeb...");

                cmds.Append("cd ~/nodejs/LircNodeJsWeb; ");

                BuildInfoEcho(cmds, "Stopping service...");

                cmds.Append("sudo systemctl stop lircnodejsweb.service; ");

                BuildInfoEcho(cmds, "Resetting git repo...");

                cmds.Append("git reset --hard; ");
                cmds.Append("echo ''; ");

                BuildInfoEcho(cmds, "Pulling latest...");

                cmds.Append("git pull; ");
                cmds.Append("echo ''; ");

                BuildInfoEcho(cmds, "Navigating to ~/nodejs/LircNodeJsWeb/Web...");

                cmds.Append("cd ~/nodejs/LircNodeJsWeb/Web; ");

                BuildInfoEcho(cmds, "Running npm install...");

                cmds.Append("npm i; ");
                cmds.Append("echo ''; ");

                BuildInfoEcho(cmds, "Starting service...");

                cmds.Append("sudo systemctl start lircnodejsweb.service; ");

                BuildInfoEcho(cmds, "Service running!");

                client.Connect();

                SshCommand cmd = client.CreateCommand(cmds.ToString());

                var result = cmd.BeginExecute();

                using (var reader = new StreamReader(cmd.OutputStream, Encoding.UTF8, true, 1024, true))
                {
                    while (!result.IsCompleted || !reader.EndOfStream)
                    {
                        string line = reader.ReadLine();

                        if (line != null)
                        {
                            Logger.Info(line);
                        }
                    }
                }

                cmd.EndExecute(result);
            }
        }
コード例 #34
0
 public SshUnzip(string buildToolsDirectory, string buildToolsZip)
 {
     _buildToolsDirectory = buildToolsDirectory;
     _buildToolsZip = buildToolsZip;
     _sshCommand = new SshCommand(_buildToolsDirectory);
 }
コード例 #35
0
ファイル: SshCommandTest.cs プロジェクト: delfinof/ssh.net
 [Ignore] // placeholder for actual test
 public void ResultTest()
 {
     Session session = null; // TODO: Initialize to an appropriate value
     string commandText = string.Empty; // TODO: Initialize to an appropriate value
     var encoding = Encoding.UTF8;
     SshCommand target = new SshCommand(session, commandText, encoding); // TODO: Initialize to an appropriate value
     string actual;
     actual = target.Result;
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
コード例 #36
0
        // SizeRun. this is a seperate thread to the tail thread. we run an appropriate command to get the size
        // of the file being tailed. If we detect the file has shrunk, we bounce the tail thread to start at
        // the begining again. We first check if the file exists and if not wait for it to appear before continuing.
        public void SizeRun()
        {
            string cmd        = sizeCmd.Replace("FILE", fileName);
            bool   warned     = false;
            bool   exists     = false;
            Int64  lastLength = 0;

            try
            {
                while (running)
                {
                    // Run the command and await the result
                    SshCommand sshCommand = ssh.CreateCommand(cmd);
                    string     result     = sshCommand.Execute();
                    result = result.TrimEnd();

                    // Get the size of the file, if line is empty the file dosnt exist set length to -1
                    Int64 length = -1;
                    if (result.Length > 0)
                    {
                        try
                        {
                            length = Int64.Parse(result);
                        }
                        catch (Exception e)
                        {
                            length = -1;
                        }
                    }

                    // if length < 0 then file dosnt exist, if it did exist previously then stop everything, otherwise
                    // just warn and try again later
                    if (length < 0)
                    {
                        Console.WriteLine("not there");
                        if (exists)
                        {
                            EnqueueLine("File " + fileName + " dosn't exist", true);
                            exists = false;
                            StopTail();
                        }
                        else
                        {
                            if (!warned)
                            {
                                warned = true;
                                EnqueueLine("File " + fileName + " dosn't exist, wait for creation...", true);
                            }
                        }
                    }
                    else
                    {
                        // file has a size. if it previously didnt exist ( which is default at start ) then
                        // write a message & start the tail thread
                        if (!exists) // new file
                        {
                            EnqueueLine("Opening " + fileName, true);
                            exists = true;
                            StartTail();
                        }
                        else
                        {
                            // if file has shrunk since last check, bounce the tail thread to get it to start
                            // from the begining
                            if (length < lastLength) // restarted file
                            {
                                EnqueueLine("File size is smaller, reopen from start " + fileName, true);
                                StopTail();
                                StartTail();
                            }
                            // otherwise everything is tickety boo
                            // record last position
                            lastLength = length;
                        }
                    }
                    // Wait a couple of seconds before re-testing but do it in a loop so we can
                    // check running state at the same time
                    for (int d = 0; d < 200 && running; d++)
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                }
            }

            catch (Exception e)
            {
                running = false;
                EnqueueLine("Error connecting:" + e.Message, true);
                throw e;
            }
        }
コード例 #37
0
        private void ResponseCallback(IAsyncResult result, Action <SshApiResponse> callback, SshCommand sshCommand)
        {
            var response = new SshApiResponse
            {
                ResponseStatus = ResponseStatus.None
            };

            //var str = string.Empty;
            try
            {
                //WaitHandle.WaitAny(new[] {result.AsyncWaitHandle});


                //var cmd = (SshCommand) result.AsyncState;

                //str = cmd.EndExecute(result);

                //var b = result.IsCompleted;

                //apiResponse.Content = str;
                using (sshCommand)
                {
                    ExtractResponseData(response, sshCommand);
                    PopulateErrorForIncompleteResponse(response, sshCommand);
                }
            }
            catch (Exception e)
            {
                response = ResponseCallbackError(e);
            }

            callback(response);
        }
コード例 #38
0
ファイル: SshCommandTest.cs プロジェクト: delfinof/ssh.net
 [Ignore] // placeholder for actual test
 public void DisposeTest()
 {
     Session session = null; // TODO: Initialize to an appropriate value
     string commandText = string.Empty; // TODO: Initialize to an appropriate value
     var encoding = Encoding.UTF8;
     SshCommand target = new SshCommand(session, commandText, encoding); // TODO: Initialize to an appropriate value
     target.Dispose();
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
コード例 #39
0
 private void ExtractResponseData(SshApiResponse apiResponse, SshCommand sshCommand)
 {
     apiResponse.Content        = sshCommand.Result;
     apiResponse.ResponseStatus = ResponseStatus.Completed;
     apiResponse.StatusCode     = sshCommand.ExitStatus;
 }
コード例 #40
0
ファイル: SshCommandTest.cs プロジェクト: delfinof/ssh.net
 [Ignore] // placeholder for actual test
 public void CommandTimeoutTest()
 {
     Session session = null; // TODO: Initialize to an appropriate value
     string commandText = string.Empty; // TODO: Initialize to an appropriate value
     var encoding = Encoding.UTF8;
     SshCommand target = new SshCommand(session, commandText, encoding); // TODO: Initialize to an appropriate value
     TimeSpan expected = new TimeSpan(); // TODO: Initialize to an appropriate value
     TimeSpan actual;
     target.CommandTimeout = expected;
     actual = target.CommandTimeout;
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
コード例 #41
0
 public void CreateCommand(string command)
 {
     _command = _client.CreateCommand(command);
 }
コード例 #42
0
        //int i = 1;
        private async void GetConnectCassandras(Object source, EventArgs e)  // Метод в таймере для casmon и создания всех соединений по SSH
        {
            DispatcherTimer timer = (DispatcherTimer)source;

            if (null != timer.Tag)
            {
                return;
            }
            try
            {
                Task <List <Casmon> > t = Task <List <Casmon> > .Run(get_cass);

                timer.Tag = t;
                await t;
            }
            catch (Exception ass)
            {
                return;
            }
            finally
            {
                timer.Tag = null;
            }

            // получение файла casmon из начального соединения и извлечение всех доступных адресов
            List <Casmon> get_cass()
            {
                casmon_list.Clear();
                try
                {
                    using (SshCommand ddd = global.sshClients[0].RunCommand("cd /etc/cassandra/; /opt/rust-bin/casmon"))
                    {
                        string  res  = ddd.Result;
                        JObject eee  = JObject.Parse(res);
                        JArray  list = (JArray)eee["seeds"];
                        global.NameClasterCassandra = (string)eee["clusetr_name"];
                        string node  = "";
                        string check = "";
                        foreach (JObject content in list.Children <JObject>())
                        {
                            foreach (JProperty prop in content.Properties())
                            {
                                if (prop.Name.ToString() == "node")
                                {
                                    node = prop.Value.ToString();
                                }
                                else
                                {
                                    check = prop.Value.ToString();
                                }
                            }
                            casmon_list.Add(new Casmon(node, check));
                        }
                    }



                    // Проверяем доступность и меняем цвет
                    this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                    {
                        if (global.casmons.Count == 0)
                        {
                            global.casmons = casmon_list;
                            radius_Elipse_Casmon(global.casmons);
                        }
                        else
                        {
                            foreach (Casmon cas in global.casmons)
                            {
                                if (cas.check == "False")
                                {
                                    //string tag = cas.node;
                                    foreach (UIElement uI in cnv.Children)
                                    {
                                        if (uI is Border)
                                        {
                                            Border border = (Border)uI;

                                            SolidColorBrush red          = new SolidColorBrush(Color.FromRgb(r_Red, g_Red, b_Red));
                                            SolidColorBrush border_color = (SolidColorBrush)border.Background;

                                            if (border.Tag.ToString() == cas.node.ToString() && red.Color != border_color.Color)
                                            {
                                                border.Background = new SolidColorBrush(Color.FromRgb(r_Yellow, g_Yellow, b_Yellow));
                                                //global.casmons = t.Result;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    foreach (UIElement uI in cnv.Children)
                                    {
                                        if (uI is Border)
                                        {
                                            Border border = (Border)uI;

                                            SolidColorBrush red          = new SolidColorBrush(Color.FromRgb(r_Red, g_Red, b_Red));
                                            SolidColorBrush border_color = (SolidColorBrush)border.Background;

                                            if (border.Tag.ToString() == cas.node.ToString() && red.Color != border_color.Color)
                                            {
                                                border.Background = new SolidColorBrush(Color.FromRgb(r_GreenE, g_GreenE, b_GreenE));
                                                //global.casmons = t.Result;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
                catch (Exception ass)
                {
                    global.sshErrors.Add(new SshError(DateTime.Now.ToLocalTime().ToString(), ass.ToString()));
                    this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                    {
                        datagrid_system.ItemsSource  = null;
                        datagrid_system.SelectedItem = null;
                        datagrid_system.ItemsSource  = global.sshErrors;
                        datagrid_system.SelectedItem = global.sshErrors;
                    });
                }
                // делаем остальные соединения по ssh если их еще не сделали
                int m = global.sshClients.Count - 1;

                if (global.sshClients.Count < casmon_list.Count) // если количество соединений меньше возможных
                {
                    foreach (Casmon casmon in casmon_list)
                    {
                        if (casmon.node != global.host)
                        {
                            m++;
                            try
                            {
                                global.sshClients.Add(new SshClient(casmon.node, global.login, global.password));
                                Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    progressBar.Visibility = Visibility.Visible;
                                });
                                global.sshClients[m].Connect();
                                Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    progressBar.Visibility = Visibility.Hidden;
                                });
                                if (global.sshClients[m].IsConnected != true)
                                {
                                    //MessageBox.Show($"Соединение SSH по адресу {cassss[i].node} не получилось установить!");

                                    /*this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate ()
                                     * {
                                     *  error_text.Text = $"Соединение SSH по адресу {casmon.node} не получилось установить! \n{COUNT}";
                                     * });
                                     * COUNT++;*/
                                }
                            }
                            catch (Exception ee)
                            {
                                //string host = global.sshClients[m].ConnectionInfo.Host;
                                string host = casmon.node;
                                Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    foreach (UIElement uI in cnv.Children)
                                    {
                                        if (uI is Border)
                                        {
                                            Border border = (Border)uI;
                                            if (border.Tag.ToString() == host.ToString())
                                            {
                                                border.Background = new SolidColorBrush(Color.FromRgb(r_Red, g_Red, b_Red));
                                            }
                                        }
                                    }
                                });



                                global.sshErrors.Add(new SshError(DateTime.Now.ToLocalTime().ToString(), ee.ToString()));
                                this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    progressBar.Visibility       = Visibility.Hidden;
                                    datagrid_system.ItemsSource  = null;
                                    datagrid_system.SelectedItem = null;
                                    datagrid_system.ItemsSource  = global.sshErrors;
                                    datagrid_system.SelectedItem = global.sshErrors;
                                });
                            }
                        }
                    }
                }
                else if (global.sshClients.Count == casmon_list.Count)  // проверка на IsConnected
                {
                    foreach (SshClient ssh_client in global.sshClients)
                    {
                        if (ssh_client.IsConnected == false)
                        {
                            try
                            {
                                Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    text_Gif_System.Visibility  = Visibility.Visible;
                                    image_Gif_System.Visibility = Visibility.Visible;
                                });
                                ssh_client.Connect();

                                // Если соединение установлено то красим в желтый
                                string host = ssh_client.ConnectionInfo.Host;
                                Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    foreach (UIElement uI in cnv.Children)
                                    {
                                        if (uI is Border)
                                        {
                                            Border border = (Border)uI;
                                            if (border.Tag.ToString() == host.ToString())
                                            {
                                                border.Background = new SolidColorBrush(Color.FromRgb(r_Yellow, g_Yellow, b_Yellow));
                                            }
                                        }
                                    }
                                });

                                Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    text_Gif_System.Visibility  = Visibility.Hidden;
                                    image_Gif_System.Visibility = Visibility.Hidden;
                                });
                            }
                            catch (Exception ass)
                            {
                                //======================================================================================================================
                                string host = ssh_client.ConnectionInfo.Host;
                                Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    foreach (UIElement uI in cnv.Children)
                                    {
                                        if (uI is Border)
                                        {
                                            Border border = (Border)uI;
                                            if (border.Tag.ToString() == host.ToString())
                                            {
                                                border.Background = new SolidColorBrush(Color.FromRgb(r_Red, g_Red, b_Red));
                                            }
                                        }
                                    }
                                });


                                global.sshErrors.Add(new SshError(DateTime.Now.ToLocalTime().ToString(), ass.ToString()));
                                this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    text_Gif_System.Visibility   = Visibility.Hidden;
                                    image_Gif_System.Visibility  = Visibility.Hidden;
                                    datagrid_system.ItemsSource  = null;
                                    datagrid_system.SelectedItem = null;
                                    datagrid_system.ItemsSource  = global.sshErrors;
                                    datagrid_system.SelectedItem = global.sshErrors;
                                });
                            }
                        }
                    }
                }

                global.sysmons.Clear();
                // получение всех sysmon файлов
                foreach (SshClient ssh in global.sshClients)
                {
                    disks.Clear();
                    try
                    {
                        using (SshCommand ddd = ssh.RunCommand("cd /etc/cassandra/; /opt/rust-bin/sysmon"))
                        {
                            string  res = ddd.Result;
                            JObject eee = JObject.Parse(res);

                            string host      = (string)eee["host"];
                            string ip        = (string)eee["ip"];
                            string os        = (string)eee["os"];
                            string version   = (string)eee["version"];
                            int    mem_total = (int)eee["mem_total"];
                            int    mem_used  = (int)eee["mem_used"];


                            JArray list        = (JArray)eee["disks"];
                            string name        = "";
                            string mount_point = "";
                            double total       = 0;
                            double used        = 0;
                            foreach (JObject content in list.Children <JObject>())
                            {
                                foreach (JProperty prop in content.Properties())
                                {
                                    if (prop.Name.ToString() == "name")
                                    {
                                        name = prop.Value.ToString();
                                    }
                                    else if (prop.Name.ToString() == "mount_point")
                                    {
                                        mount_point = prop.Value.ToString();
                                    }
                                    else if (prop.Name.ToString() == "total")
                                    {
                                        total = (double)prop.Value;
                                    }
                                    else if (prop.Name.ToString() == "used")
                                    {
                                        used = (double)prop.Value;
                                    }
                                }
                                disks.Add(new Disk(name, mount_point, total.ToString(), used.ToString()));
                            }
                            global.sysmons.Add(new Sysmon(host, ip, os, version, mem_total, mem_used, disks));
                            if (!setBoolNameClaster)  // устанавливаем имя кластера
                            {
                                nameClaster = global.sysmons[0].host;
                                this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    cassandra_Name(nameClaster);
                                });
                                setBoolNameClaster = true;
                            }
                        }
                    }
                    catch (Exception ass)
                    {
                        global.sshErrors.Add(new SshError(DateTime.Now.ToLocalTime().ToString(), ass.ToString()));
                        this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                        {
                            datagrid_system.ItemsSource  = null;
                            datagrid_system.SelectedItem = null;
                            datagrid_system.ItemsSource  = global.sshErrors;
                            datagrid_system.SelectedItem = global.sshErrors;
                        });
                    }
                }
                return(casmon_list);
            }
        }
コード例 #43
0
 public bool WasSuccess(SshCommand command)
 {
     return(command.ExitStatus == 0);
 }