martes, 18 de enero de 2011

Ejemplo en C# para ejecutar comandos remotos en UNIX usando REXEC


Esta clase tiene como propósito brindar a aplicaciones .NET la capacidad de interactuar con el protocolo REXEC, descrito en el RFC 2179, en seguida el listado de código.





using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace F.Net.Protocols
{
    /// <summary>
    /// rexec Protocol Class Handler
    /// written by Bonifacio Castillo 09 Aug 06
    /// as part of F in "F.Net.Protocols" namespace
    /// </summary>
    public class rexec
    {
        #region Enumerations
        /// <summary>
        /// Execution Method Enumarate [BySocket=0, ByTCPClient=1] 
        /// </summary>
        public enum ExecutionMethod
        {
            BySocket = 0,
            ByTCPClient = 1
        }
        #endregion

        #region Private Members
        private string _server;
        private string _user;
        private string _password;
        private string _command;
        private string _response;
        private byte[] _received;
        private int _port;
        private int _buffersize;
        private byte[] packet;
        private ExecutionMethod exMethod = rexec.ExecutionMethod.ByTCPClient;
        private int sendTiemout;
        private int receiveTimeout;
        #endregion

        #region Properties
        /// <summary>
        /// Message Send Timeout
        /// </summary>
        public int SendTimeOut
        {
            set
            {
                sendTiemout = value;
            }
            get
            {
                return sendTiemout;
            }
        }
        /// <summary>
        /// Response Receive Timeout
        /// </summary>
        public int ReceiveTimeOut
        {
            set
            {
                receiveTimeout = value;
            }
            get
            {
                return receiveTimeout;
            }
        }
        /// <summary>
        /// Execution Method, select between By Using Socket's or TCPclient
        /// </summary>
        public ExecutionMethod ExecMethod
        {
            set
            {
                exMethod = value;
            }
            get
            {
                return exMethod;

            }
        }
        /// <summary>
        /// Reading BufferSize
        /// </summary>
        public int BufferSize
        {
            set
            {
                _buffersize = value;
            }
            get
            {
                return _buffersize;

            }
        }
        /// <summary>
        /// Server Name or IP address
        /// </summary>
        public string Host
        {
            set
            {
                _server = value;
            }
            get
            {
                return _server;
            }
        }

        /// <summary>
        /// Remote user identifier
        /// </summary>
        public string User
        {
            set
            {
                _user = value;
            }
            get
            {
                return _user;
            }
        }
        /// <summary>
        /// Remote user password
        /// </summary>
        public string Password
        {
            set
            {
                _password = value;
            }
            get
            {
                return _password;
            }
        }
        /// <summary>
        /// Command to be Sent
        /// </summary>
        public string Command
        {
            set
            {
                _command = value;
            }
            get
            {
                return _command;
            }
        }
        /// <summary>
        /// Command Response
        /// </summary>
        public string Response
        {
            get
            {
                return _response;
            }
        }
        /// <summary>
        /// rexec service listening port
        /// </summary>
        public int Port
        {
            set
            {
                _port = value;
            }
            get
            {
                return _port;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public byte[] Received
        {
            get
            {
                return _received;
            }
        }

        #endregion

        #region Constructors
        private void Init()
        {
            this.receiveTimeout = 1000;
            this.sendTiemout = 1000;
            this._buffersize = 4096;
            this._port = 512;
        }
        //
        public rexec()
        {
            Init();
        }
        /// <summary>
        /// rexec Clas constructor
        /// </summary>
        /// <param name="server">Server Name or IP address</param>
        /// <param name="port">rexec port usually 512</param>
        /// <param name="user">remote userid</param>
        /// <param name="password">remote user password</param>
        /// <param name="command">command to execute</param>
        public rexec(int buffSize, int recTimeOut, int senTimeout, string server, int port, string user, string password, string command)
        {
            Init();
            this._buffersize = buffSize;
            this.receiveTimeout = recTimeOut;
            this.sendTiemout = senTimeout;
            this._server = server;
            this._port = port;
            this._password = password;
            this._user = user;
            this._command = command;
        }
        /// <summary>
        /// rexec Clas constructor
        /// </summary>
        /// <param name="server">Server Name or IP address</param>
        /// <param name="port">rexec port usually 512</param>
        /// <param name="user">remote userid</param>
        /// <param name="password">remote user password</param>
        /// <param name="command">command to execute</param>
        public rexec(int recTimeOut, int senTimeout, string server, int port, string user, string password, string command)
        {
            Init();
            this.receiveTimeout = recTimeOut;
            this.sendTiemout = senTimeout;
            this._server = server;
            this._port = port;
            this._password = password;
            this._user = user;
            this._command = command;
        }
        /// <summary>
        /// rexec Clas constructor
        /// </summary>
        /// <param name="server">Server Name or IP address</param>
        /// <param name="port">rexec port usually 512</param>
        /// <param name="user">remote userid</param>
        /// <param name="password">remote user password</param>
        /// <param name="command">command to execute</param>
        public rexec(string server, int port, string user, string password, string command)
        {
            Init();
            this._server = server;
            this._port = port;
            this._password = password;
            this._user = user;
            this._command = command;
        }
        /// <summary>
        /// rexec Clas constructor
        /// </summary>
        /// <param name="server">Server Name or IP address</param>
        /// <param name="user">remote userid</param>
        /// <param name="password">remote user password</param>
        /// <param name="command">command to execute</param>
        public rexec(string server, string user, string password, string command)
        {
            Init();
            this._server = server;
            this._port = 512;
            this._password = password;
            this._user = user;
            this._command = command;
        }
        #endregion

        #region Methods
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private string BuildPacket()
        {
            try
            {
                string Message = '\0' + this._user + '\0' + this._password + '\0' + this._command + '\0';
                return Message;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Connect's to rexecd and send it a command using TCPClient
        /// </summary>
        /// <param name="server">Server Name or IP address</param>
        /// <param name="message">Message to send as a Network Packet</param>
        private void Connect(string server, string message)
        {
            try
            {

                Int32 bytes;
                // Create a TcpClient.
                // Note, for this client to work you need to have a TcpServer 
                // connected to the same address as specified by the server, port
                // combination.

                TcpClient client = new TcpClient(server, this._port);
                client.ReceiveTimeout = receiveTimeout;
                client.SendTimeout = sendTiemout;

                // Translate the passed message into ASCII and store it as a Byte array.
                this.packet = System.Text.Encoding.UTF8.GetBytes(message);

                // Get a client stream for reading and writing.
                //  Stream stream = client.GetStream();

                NetworkStream stream = client.GetStream();

                // Send the message to the connected TcpServer. 
                stream.Write(packet, 0, packet.Length);

                // Receive the TcpServer.response.

                // Buffer to store the response bytes.
                this._received = new Byte[_buffersize];

                do
                {
                    // Read the first batch of the TcpServer response bytes.
                    bytes = stream.Read(this._received, 0, this._received.Length);
                    this._response += System.Text.Encoding.UTF8.GetString(this._received, 0, bytes).Replace("\0", "");



                } while (bytes > 0);
                // Close everything.
                client.Close();
            }
            catch (ArgumentNullException e)
            {
                throw e;
            }
            catch (SocketException e)
            {
                throw e;
            }
        }
        /// <summary>
        /// Prepare and Open a TCP Socket
        /// </summary>
        /// <param name="server">Server Name or IP address</param>
        /// <param name="port">Target Port for Socket</param>
        /// <returns></returns>
        private static Socket ConnectSocket(string server, int port)
        {
            Socket s = null;
            IPHostEntry hostEntry = null;

            // Get host related information.
            hostEntry = Dns.Resolve(server);

            // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
            // an exception that occurs when the host IP Address is not compatible with the address family
            // (typical in the IPv6 case).
            foreach (IPAddress address in hostEntry.AddressList)
            {
                IPEndPoint ipe = new IPEndPoint(address, port);
                Socket tempSocket =
                    new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                tempSocket.Connect(ipe);

                if (tempSocket.Connected)
                {
                    s = tempSocket;
                    break;
                }
                else
                {
                    continue;
                }
            }
            return s;
        }

        /// <summary>
        /// Connect's to rexecd and send it a command using socket
        /// </summary>
        /// <param name="server">Server Name or IP address</param>
        /// <param name="port">rexec Port By Defect 512</param>
        /// <returns></returns>
        private string Connect(string server, int port)
        {
            string request = this.BuildPacket();
            Byte[] bytesSent = System.Text.Encoding.UTF8.GetBytes(request);
            Byte[] bytesReceived = new Byte[this._buffersize];


            // Create a socket connection with the specified server and port.
            Socket s = ConnectSocket(server, port);

            if (s == null)
                return ("Connection failed");

            // Send request to the server.
            s.Send(bytesSent, bytesSent.Length, 0);

            // Receive the server home page content.
            int bytes = 0;
            string response = string.Empty;

            // The following will block until data is transmitted.
            do
            {
                bytes = s.Receive(bytesReceived, bytesReceived.Length, System.Net.Sockets.SocketFlags.None);
                response += System.Text.Encoding.UTF8.GetString(bytesReceived, 0, bytes);


            }
            while (bytes > 0);
            
             s.Close();

            return response.Replace("\0", "");
        }
        /// <summary>
        /// Execute the REMOTE command By rexec protocol
        /// </summary>        
        public void Execute()
        {
            if (this.exMethod == rexec.ExecutionMethod.BySocket)
                this._response = this.Connect(this._server, this._port);
            else
                this.Connect(this._server, this.BuildPacket());

        }
        #endregion

    }
}

Transacciones Fiori

  /UI2/CACHE Register service for UI2 cache use /UI2/CACHE_DEL Delete cache entries /UI2/CHIP Chip Registration /UI2/CUST Customizing of UI ...