Represents SSH command that can be executed.
Inheritance: IDisposable
示例#1
0
        public override NodeResult Run()
        {
            if (string.IsNullOrEmpty(host.Value) || string.IsNullOrEmpty(user.Value) || string.IsNullOrEmpty(command.Value))
            {
                return(NodeResult.Fail);
            }

            try
            {
                SshClient sshClient = new SshClient(host.Value, port.Value, user.Value, password.Value);
                sshClient.Connect();

                Renci.SshNet.SshCommand sshCommand = sshClient.RunCommand(command.Value);
                Log.Info(sshCommand.CommandText);

                if (!string.IsNullOrWhiteSpace(sshCommand.Result))
                {
                    Log.Warning(sshCommand.Result);
                }
                if (!string.IsNullOrWhiteSpace(sshCommand.Error))
                {
                    Log.Error(sshCommand.Error);
                }
            }
            catch (Exception e)
            {
                Log.Error(e.Message);
                return(NodeResult.Fail);
            }

            return(NodeResult.Success);
        }
示例#2
0
        public virtual String ExecuteCommand(string commandText)
        {
            if (!SshClient.IsConnected)
                SshClient.Connect();

            this.Command = SshClient.CreateCommand(commandText);
            return this.Command.Execute();
        }
 /// <summary>
 /// Creates a new command state instance.
 /// </summary>
 /// <param name="node">The PlanetLab node state.</param>
 /// <param name="command">The secure shell command.</param>
 /// <param name="exception">The subcommand exception.</param>
 public PlManagerSubcommandState(PlManagerNodeState node, SshCommand command, Exception exception)
 {
     this.Node = node;
     this.Command = command.CommandText;
     this.Timeout = command.CommandTimeout;
     this.ExitStatus = command.ExitStatus;
     this.Result = command.Result;
     this.Error = command.Error;
     this.Exception = exception;
 }
 /// <summary>
 /// Creates a new command state instance.
 /// </summary>
 /// <param name="node">The PlanetLab node state.</param>
 /// <param name="command">The secure shell command.</param>
 /// <param name="duration">The subcommand duration.</param>
 /// <param name="retries">The number of retries for this command.</param>
 public PlManagerSubcommandState(PlManagerNodeState node, SshCommand command, TimeSpan duration, int retries)
 {
     this.Node = node;
     this.Command = command.CommandText;
     this.Timeout = command.CommandTimeout;
     this.ExitStatus = command.ExitStatus;
     this.Result = command.Result;
     this.Error = command.Error;
     this.Duration = duration;
     this.Retries = retries;
 }
示例#5
0
        public override NodeResult Run()
        {
            if (authentication.Value == AuthenticationType.Password && (string.IsNullOrEmpty(host.Value) || string.IsNullOrEmpty(user.Value) || string.IsNullOrEmpty(command.Value)))
            {
                return(NodeResult.Fail);
            }
            if (authentication.Value == AuthenticationType.Certificate && (string.IsNullOrEmpty(host.Value) || string.IsNullOrEmpty(command.Value) || certificate.Value == null))
            {
                return(NodeResult.Fail);
            }

            try
            {
                SshClient sshClient;
                if (authentication.Value == AuthenticationType.Certificate && string.IsNullOrEmpty(passphrase.Value))
                {
                    sshClient = new SshClient(host.Value, port.Value, user.Value, new PrivateKeyFile(certificate.Value.FullName));
                }
                else if (authentication.Value == AuthenticationType.Certificate && !string.IsNullOrEmpty(passphrase.Value))
                {
                    sshClient = new SshClient(host.Value, port.Value, user.Value, new PrivateKeyFile(certificate.Value.FullName, passphrase.Value));
                }
                else
                {
                    sshClient = new SshClient(host.Value, port.Value, user.Value, password.Value);
                }

                sshClient.Connect();

                Renci.SshNet.SshCommand sshCommand = sshClient.RunCommand(command.Value);
                Log.Info(sshCommand.CommandText);

                if (!string.IsNullOrWhiteSpace(sshCommand.Result))
                {
                    Log.Warning(sshCommand.Result);
                }
                if (!string.IsNullOrWhiteSpace(sshCommand.Error))
                {
                    Log.Error(sshCommand.Error);
                }
            }
            catch (Exception e)
            {
                Log.Error(e.Message);
                return(NodeResult.Fail);
            }

            return(NodeResult.Success);
        }
示例#6
0
        /// <summary>
        /// Dispose(bool disposing) executes in two distinct scenarios.
        /// If disposing equals true, the method has been called directly
        /// or indirectly by a user's code. Managed and unmanaged resources
        /// can be disposed.
        /// If disposing equals false, the method has been called by the
        /// runtime from inside the finalizer and you should not reference
        /// other objects. Only unmanaged resources can be disposed.
        /// </summary>
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!this._disposed)
            {
                // Note disposing has been done.
                _disposed = true;

                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if (disposing)
                {
                    if (_sshCommand != null)
                    {
                        _sshCommand.Dispose();
                    }
                }

                // Call the appropriate methods to clean up
                // unmanaged resources here.
                _sshCommand = null;
            }
        }
		private void BeginService()
		{
			_client = new SshClient(Host, UserName, Password);
			_client.Connect();
            _client.RunCommand("sudo pkill mono");
			var call = string.Format("cd {0}", _homePiBuildindicatronServer);
			const string commandText = "sudo mono BuildIndicatron.Server.exe";
			var text = call + " && " + commandText;
			_log.Info("Starting command:" + text);
			_runCommand = _client.CreateCommand(text);
			_beginExecute = _runCommand.BeginExecute();
			streamReader = new StreamReader(_runCommand.OutputStream);
			WaitFor("Running", 6000).Wait();
		}
示例#8
0
 /// <summary>
 /// An event handler called when the client begins executing a command.
 /// </summary>
 /// <param name="command">The command.</param>
 protected virtual void OnCommandBegin(SshCommand command)
 {
 }
示例#9
0
 /// <summary>
 /// An action called when a command failed.
 /// </summary>
 /// <param name="command">The command.</param>
 /// <param name="error">The error.</param>
 private void OnCommandFailedInternal(SshCommand command, string error)
 {
     // Execute the code on the UI thread.
     this.Invoke(() =>
         {
             this.OnCommandFailed(command, error);
         });
 }
示例#10
0
 /// <summary>
 /// An action called when a command completed successfully.
 /// </summary>
 /// <param name="command">The command.</param>
 /// <param name="result">The result.</param>
 private void OnCommandSucceededInternal(SshCommand command, string result)
 {
     // Execute the code on the UI thread.
     this.Invoke(() =>
         {
             this.OnCommandSucceeded(command, result);
         });
 }
示例#11
0
 /// <summary>
 /// An action called when the client begins executing a command.
 /// </summary>
 /// <param name="command">The command.</param>
 private void OnCommandBeginInternal(SshCommand command)
 {
     // Execute the code on the UI thread.
     this.Invoke(() =>
         {
             this.OnCommandBegin(command);
         });
 }
示例#12
0
 /// <summary>
 /// An action called when the client receives data for an executing command.
 /// </summary>
 /// <param name="command">The command.</param>
 /// <param name="data">The data.</param>
 private void OnCommandDataInternal(SshCommand command, string data)
 {
     // Execute the code on the UI thread.
     this.Invoke(() =>
         {
             this.OnCommandData(command, data);
         });
 }
示例#13
0
 private int GetUserId()
 {
     using (var cmd = new SshCommand(Session, "id -u "))
         // Thease commands seems to be POSIX so the only problem would be Windows enviroment
     {
         cmd.Execute();
         return cmd.ExitStatus == 0 ? Int32.Parse(cmd.Result) : -1;
     }
 }
示例#14
0
 /// <summary>
 /// Initializes new Ssh Command spawnable.
 /// </summary>
 /// <param name="command">Ssh command to be run.</param>
 public SshCommandSpawanble(SshCommand command)
 {
     this.command = command;
 }
示例#15
0
        private int GetUserId()
        {
            if (!_noSSHCommands)
            {
                using (var cmd = new SshCommand(Session, "id -u ", Encoding.ASCII))
                // Thease commands seems to be POSIX so the only problem would be Windows enviroment
                {
                    cmd.CommandTimeout = TimeSpan.FromSeconds(10);
                    try
                    {
                        cmd.Execute();
                        if (cmd.ExitStatus == 0)
                            return Int32.Parse(cmd.Result);
                    }
                    catch
                    {
                        _noSSHCommands = true;
                    }
                }
            }

            var r = _sftpSession.RequestStat(".", true);
            if (r != null)
                return r.UserId;

            return -1;
        }
示例#16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CommandAsyncResult"/> class.
 /// </summary>
 /// <param name="command">The command.</param>
 internal CommandAsyncResult(SshCommand command)
 {
     this._command = command;
 }
示例#17
0
        DokanError IDokanOperations.GetDiskFreeSpace(out long free, out long total,
                                                     out long used, DokanFileInfo info)
        {
            Log("GetDiskFreeSpace");

            var diskSpaceInfo = _cache.Get(_volumeLabel) as Tuple<long, long, long>;

            if (diskSpaceInfo != null)
            {
                free = diskSpaceInfo.Item1;
                total = diskSpaceInfo.Item2;
                used = diskSpaceInfo.Item3;
            }
            else
            {

                if (_supportsStatVfs)
                {
                    var information = _sftpSession.RequestStatVfs(_rootpath, true);
                    total = (long)(information.TotalBlocks * information.BlockSize);
                    free = (long)(information.FreeBlocks * information.BlockSize);
                    used = (long)(information.AvailableBlocks * information.BlockSize);
                }
                else
                {
                    total = 0x1900000000; //100 GiB
                    used = 0xc80000000; // 50 Gib
                    free = 0xc80000000;

                    if (!_noSSHCommands)
                    {
                        using (var cmd = new SshCommand(Session, String.Format(" df -Pk  {0}", _rootpath), Encoding.ASCII))
                        // POSIX standard df
                        {
                            cmd.CommandTimeout = TimeSpan.FromSeconds(10);

                            try
                            {
                                cmd.Execute();
                                if (cmd.ExitStatus == 0)
                                {
                                    var values = cmd.Result.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                                    total = Int64.Parse(values[values.Length - 5]) << 10;
                                    used = Int64.Parse(values[values.Length - 4]) << 10;
                                    free = Int64.Parse(values[values.Length - 3]) << 10; //<======maybe to cache all this
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                }

                _cache.Add(_volumeLabel, new Tuple<long, long, long>(free, total, used),
                           DateTimeOffset.UtcNow.AddMinutes(3));
            }

            return DokanError.ErrorSuccess;
        }
 /// <summary>
 /// An event handler called when the client receives data for an executing command.
 /// </summary>
 /// <param name="command">The command.</param>
 /// <param name="data">The received data.</param>
 protected override void OnCommandData(SshCommand command, string data)
 {
     // Set the exception message as a result argument.
     this.console.AppendText(data, Color.LightGray);
 }
 /// <summary>
 /// An event handler called when a client command has failed.
 /// </summary>
 /// <param name="command">The command.</param>
 /// <param name="error">The error.</param>
 protected override void OnCommandFailed(SshCommand command, string error)
 {
     // Set the exception message as a result argument.
     if (!string.IsNullOrWhiteSpace(error))
     {
         this.console.AppendText(error, Color.LightGray);
     }
     this.console.AppendText("FAIL", Color.Red);
     this.console.AppendText(" Code: {0}.", command.ExitStatus);
     this.console.AppendText(Environment.NewLine);
     // Call the command complete event handler.
     this.console.EndCommand();
 }
 /// <summary>
 /// An event handler called when a client command completed successfully.
 /// </summary>
 /// <param name="command">The command.</param>
 /// <param name="result">The result.</param>
 protected override void OnCommandSucceeded(SshCommand command, string result)
 {
     // Set the exception message as a result argument.
     this.console.AppendText(result, Color.LightGray);
     this.console.AppendText("SUCCESS", Color.Lime);
     this.console.AppendText(" Code: {0}.{1}", command.ExitStatus, Environment.NewLine);
     // Call the command complete event handler.
     this.console.EndCommand();
 }
 /// <summary>
 /// An event handler called when the client begins executing a command.
 /// </summary>
 /// <param name="command">The command.</param>
 protected override void OnCommandBegin(SshCommand command)
 {
     // Begin the command.
     this.console.BeginCommand(command.CommandText);
 }
示例#22
0
        private IEnumerable<int> GetUserGroupsIds()
        {
            if (!_noSSHCommands)
            {
                using (var cmd = new SshCommand(Session, "id -G ", Encoding.ASCII))
                {
                    cmd.CommandTimeout = TimeSpan.FromSeconds(10);
                    try
                    {
                        {
                            cmd.Execute();
                            return cmd.Result.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(Int32.Parse);
                        }
                    }
                    catch
                    {
                        _noSSHCommands = true;
                    }
                }
            }

            var r = _sftpSession.RequestStat(".", true);
            if (r != null)
                return new int[] { r.GroupId };

            return new int[0];
        }
示例#23
0
 /// <summary>
 /// An event handler called when the client receives data for an executing command.
 /// </summary>
 /// <param name="info">The connection info.</param>
 /// <param name="command">The command.</param>
 /// <param name="data">The received data.</param>
 protected virtual void OnCommandData(SshCommand command, string data)
 {
 }
示例#24
0
 public SshProcess(SshCommand process)
 {
     _command = process;
 }
示例#25
0
 /// <summary>
 /// An event handler called when a client command has failed.
 /// </summary>
 /// <param name="command">The command.</param>
 /// <param name="error">The error.</param>
 protected virtual void OnCommandFailed(SshCommand command, string error)
 {
 }
示例#26
0
 private IEnumerable<int> GetUserGroupsIds()
 {
     using (var cmd = new SshCommand(Session, "id -G "))
     {
         cmd.Execute();
         return cmd.Result.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries).Select(Int32.Parse);
     }
 }
示例#27
0
 /// <summary>
 /// An event handler called when a client command completed successfully.
 /// </summary>
 /// <param name="command">The command.</param>
 /// <param name="result">The result.</param>
 protected virtual void OnCommandSucceeded(SshCommand command, string result)
 {
 }
示例#28
0
        DokanError IDokanOperations.GetDiskFreeSpace(out long free, out long total,
            out long used, DokanFileInfo info)
        {
            //Log("GetDiskFreeSpace");
            LogFSActionInit("GetDiskFreeSpace", this._volumeLabel, (SftpContext)info.Context, "");

            Log("GetDiskFreeSpace");

            var diskSpaceInfo = CacheGetDiskInfo();

            if (diskSpaceInfo != null)
            {
                free = diskSpaceInfo.Item1;
                total = diskSpaceInfo.Item2;
                used = diskSpaceInfo.Item3;
            }
            else
            {
                if (_supportsStatVfs)
                {
                    var information = _sftpSession.RequestStatVfs(_rootpath, true);
                    total = (long) (information.TotalBlocks*information.BlockSize);
                    free = (long) (information.FreeBlocks*information.BlockSize);
                    used = (long) (information.AvailableBlocks*information.BlockSize);
                }
                else
                    using (var cmd = new SshCommand(Session, String.Format(" df -Pk  {0}", _rootpath)))
                        // POSIX standard df
                    {
                        cmd.Execute();
                        if (cmd.ExitStatus == 0)
                        {
                            var values = cmd.Result.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);

                            total = Int64.Parse(values[values.Length - 5]) << 10;
                            used = Int64.Parse(values[values.Length - 4]) << 10;
                            free = Int64.Parse(values[values.Length - 3]) << 10; //<======maybe to cache all this
                        }
                        else
                        {
                            total = 0x1900000000; //100 GiB
                            used = 0xc80000000; // 50 Gib
                            free = 0xc80000000;
                        }
                    }

                CacheAddDiskInfo(new Tuple<long, long, long>(free, total, used),
                        DateTimeOffset.UtcNow.AddMinutes(3));
            }
            LogFSActionSuccess("GetDiskFreeSpace", this._volumeLabel, (SftpContext)info.Context, "Free:{0} Total:{1} Used:{2}", free, total, used);
            return DokanError.ErrorSuccess;
        }
示例#29
0
 public void CreateCommand(string command)
 {
     _command = _client.CreateCommand(command);
 }