telnet制御ルータスイッチと微信公衆プラットフォーム

25111 ワード

もとはすべての機械室を制御してインターネットを利用するのはすべてスイッチのweb管理ページからスイッチのポートを操作するので、単位が鋭いルートとスイッチを交換してから穴のお父さんになって、web管理さえなくて、スイッチのポートなどはすべてtelnetに上陸するたびに、たくさんの指令、それから私は微信の公衆のプラットフォームを手に入れて公衆のプラットフォームでスイッチのポートを制御することを考えて、実現後の効果鉄棒の、私の微信は101 openを入力して、101のネットは開いて、101 close、101のネットは切って、家で単位で、地下鉄で、トイレで......勝手な制御がすぐに有効になる現在の考え方は,微信発命令からサービス側へ->サービス側書込み操作情報からデータベース->サーバ上の命令実行器データベース内の命令実行が完了した後に結果を保存することである.
 
telnet   

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Threading;


public class Telnet
{
    #region telnet     
    /// <summary>        
    ///    ,     TELNET           
    /// </summary>        
    readonly Char IAC = Convert.ToChar(255);
    /// <summary>        
    ///            ,                 。
    /// </summary>        
    readonly Char DO = Convert.ToChar(253);
    /// <summary>
    ///              ,                   。       
    /// </summary>       
    readonly Char DONT = Convert.ToChar(254);
    /// <summary>
    ///                       。
    /// </summary>
    readonly Char WILL = Convert.ToChar(251);
    /// <summary>
    ///                  。
    /// </summary>
    readonly Char WONT = Convert.ToChar(252);
    /// <summary>
    ///                   
    /// </summary>
    readonly Char SB = Convert.ToChar(250);
    /// <summary>
    ///         
    /// </summary>
    readonly Char SE = Convert.ToChar(240);
    const Char IS = '0';
    const Char SEND = '1';
    const Char INFO = '2';
    const Char VAR = '0';
    const Char VALUE = '1';
    const Char ESC = '2';
    const Char USERVAR = '3';
    /// <summary> 
    ///  
    /// /// </summary>
    byte[] m_byBuff = new byte[100000];
    /// <summary>
    ///        
    /// </summary>
    private ArrayList m_ListOptions = new ArrayList();
    /// <summary>
    ///          
    /// </summary>
    string m_strResp;
    /// <summary>
    ///   Socket   
    /// </summary>
    private Socket s;
    #endregion

    private IPEndPoint iep;
    private string address;
    private int port;
    private int timeout;

    private string strWorkingData = "";     //              
    private string strFullLog = "";
    //====================================================            

    private string strWorkingDataX = "";
    //             

    public string WorkingData
    {
        get { return strWorkingDataX; }
    }
    //===================================================================
    public Telnet(string Address, int Port, int CommandTimeout)
    {
        address = Address;
        port = Port;
        timeout = CommandTimeout;
    }

    /// <summary>        
    ///   socket   telnet          
    /// </summary>       
    public bool Connect()
    {

        IPAddress import = GetIP(address);

        s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        iep = new IPEndPoint(import, port);

        try
        {
            // Try a blocking connection to the server
            s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            s.Connect(iep);

            //    
            AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
            s.BeginReceive(m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, s);

            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

    /// <summary>        
    ///       ,     (     )       
    /// </summary>      
    /// <param name="ar"></param>       
    private void OnRecievedData(IAsyncResult ar)
    {
        try
        {
            //        socket              
            Socket sock = (Socket)ar.AsyncState;

            //EndReceive                     
            int nBytesRec = sock.EndReceive(ar);
            //                      
            if (nBytesRec > 0)
            {
                //       ,                           
                string m_strLine = "";
                //  Socket                       
                /*       
                 *        linux   windows                
                 *              m_strLine      
                 */
                for (int i = 0; i < nBytesRec; i++)
                {
                    Char ch = Convert.ToChar(m_byBuff[i]);
                    switch (ch)
                    {
                        case '\r':
                            m_strLine += Convert.ToString("\r
"); break; case '
': break; default: m_strLine += Convert.ToString(ch); break; } } try { // int strLinelen = m_strLine.Length; // if (strLinelen == 0) { // "\r
" m_strLine = Convert.ToString("\r
"); } // , ( ) mToProcess Byte[] mToProcess = new Byte[strLinelen]; for (int i = 0; i < strLinelen; i++) mToProcess[i] = Convert.ToByte(m_strLine[i]); // , string mOutText = ProcessOptions(mToProcess); //================================================= mOutText = ConvertToGB2312(mOutText); strWorkingDataX = mOutText; //=================================================================== // ( ) if (mOutText != "") { //Console.Write(mOutText);// // 20110531///////////////////////// strWorkingData = mOutText; strFullLog += mOutText; } // , , RespondToOptions(); } catch (Exception ex) { throw new Exception(" ! " + ex.Message); } } else// { // // socket sock.Shutdown(SocketShutdown.Both); sock.Close(); } } catch { } } /// <summary> /// /// </summary> private void RespondToOptions() { try { // , string strOption; /* * , * 255 253 23 */ for (int i = 0; i < m_ListOptions.Count; i++) { // strOption = (string)m_ListOptions[i]; // , ArrangeReply(strOption); } DispatchMessage(m_strResp); m_strResp = ""; m_ListOptions.Clear(); } catch (Exception ers) { Console.WriteLine(" , " + ers.Message); } } /// <summary> /// , , ///</summary> ///<param name="m_strLineToProcess"> </param> /// <returns></returns> private string ProcessOptions(byte[] m_strLineToProcess) { string m_DISPLAYTEXT = ""; string m_strTemp = ""; string m_strOption = ""; string m_strNormalText = ""; bool bScanDone = false; int ndx = 0; int ldx = 0; char ch; try { // byte[] string for (int i = 0; i < m_strLineToProcess.Length; i++) { Char ss = Convert.ToChar(m_strLineToProcess[i]); m_strTemp = m_strTemp + Convert.ToString(ss); } // , , while (bScanDone != true) { // int lensmk = m_strTemp.Length; // , 255 , ndx = m_strTemp.IndexOf(Convert.ToString(IAC)); // , if (ndx > lensmk) ndx = m_strTemp.Length; // , IAC telnet , if (ndx != -1) { #region IAC // IAC m_DISPLAYTEXT += m_strTemp.Substring(0, ndx); // ch = m_strTemp[ndx + 1]; // 253(DO) 254(DONT) 521(WILL) 252(WONT) if (ch == DO || ch == DONT || ch == WILL || ch == WONT) { // IAC 3 m_strOption = m_strTemp.Substring(ndx, 3); m_ListOptions.Add(m_strOption); // IAC m_DISPLAYTEXT += m_strTemp.Substring(0, ndx); // string txt = m_strTemp.Substring(ndx + 3); m_strTemp = txt; } // IAC IAC (255) else if (ch == IAC) { // , IAC m_DISPLAYTEXT = m_strTemp.Substring(0, ndx); // m_strTemp = m_strTemp.Substring(ndx + 1); } // IAC SB(250) else if (ch == SB) { m_DISPLAYTEXT = m_strTemp.Substring(0, ndx); ldx = m_strTemp.IndexOf(Convert.ToString(SE)); m_strOption = m_strTemp.Substring(ndx, ldx); m_ListOptions.Add(m_strOption); m_strTemp = m_strTemp.Substring(ldx); } #endregion } // IAC else { // m_strTemp m_DISPLAYTEXT = m_DISPLAYTEXT + m_strTemp; bScanDone = true; } } // m_strNormalText = m_DISPLAYTEXT; } catch (Exception eP) { throw new Exception(" :" + eP.Message); } return m_strNormalText; } /// <summary> /// IP /// </summary> /// <param name="import"></param> /// <returns></returns> private static IPAddress GetIP(string import) { IPHostEntry IPHost = Dns.GetHostEntry(import); return IPHost.AddressList[0]; } #region magic Function // , m_strResp private void ArrangeReply(string strOption) { try { Char Verb; Char Option; Char Modifier; Char ch; bool bDefined = false; // , if (strOption.Length < 3) return; // Verb = strOption[1]; // Option = strOption[2]; // (1) (3) if (Option == 1 || Option == 3) { bDefined = true; } // , 255 m_strResp += IAC; // (1) (3) ==true if (bDefined == true) { #region // 253 (DO) if (Verb == DO) { // 251(WILL) ch = WILL; m_strResp += ch; m_strResp += Option; } // 254(DONT) if (Verb == DONT) { // 252(WONT) " " ch = WONT; m_strResp += ch; m_strResp += Option; } // 251(WILL) if (Verb == WILL) { // 253(DO) ch = DO; m_strResp += ch; m_strResp += Option; //break; } // 251(WONT) if (Verb == WONT) { // ch = DONT; m_strResp += ch; m_strResp += Option; //break; } // 250(sb, ) if (Verb == SB) { /* * , 4 , * * 1(send) * 250(SB ) + + 0(is) + 255( IAC) + 240(SE ) */ Modifier = strOption[3]; if (Modifier == SEND) { ch = SB; m_strResp += ch; m_strResp += Option; m_strResp += IS; m_strResp += IAC; m_strResp += SE; } } #endregion } else // 1 3 { #region , , if (Verb == DO) { ch = WONT; m_strResp += ch; m_strResp += Option; } if (Verb == DONT) { ch = WONT; m_strResp += ch; m_strResp += Option; } if (Verb == WILL) { ch = DONT; m_strResp += ch; m_strResp += Option; } if (Verb == WONT) { ch = DONT; m_strResp += ch; m_strResp += Option; } #endregion } } catch (Exception eeeee) { throw new Exception(" :" + eeeee.Message); } } /// <summary> /// charp[] , socket /// , , , /// , , OnRecieveData /// /// </summary> /// <param name="strText"></param> void DispatchMessage(string strText) { try { // char Byte[] smk = new Byte[strText.Length]; for (int i = 0; i < strText.Length; i++) { // , char Byte ss = Convert.ToByte(strText[i]); smk[i] = ss; } // char , ( ) IAsyncResult ar2 = s.BeginSend(smk, 0, smk.Length, SocketFlags.None, delegate(IAsyncResult ar) { // " " // Socket , beginsend Socket sock1 = (Socket)ar.AsyncState; if (sock1.Connected)// { // AsyncCallback recieveData = new AsyncCallback(OnRecievedData); sock1.BeginReceive(m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, sock1); } }, s); s.EndSend(ar2); } catch (Exception ers) { Console.WriteLine(" , :" + ers.Message); } } /// <summary> /// /// </summary> /// <param name="DataToWaitFor"> </param> /// <returns> 0</returns> public int WaitFor(string DataToWaitFor) { long lngStart = DateTime.Now.AddSeconds(this.timeout).Ticks; long lngCurTime = 0; while (strWorkingData.ToLower().IndexOf(DataToWaitFor.ToLower()) == -1) { lngCurTime = DateTime.Now.Ticks; if (lngCurTime > lngStart) { throw new Exception("Timed Out waiting for : " + DataToWaitFor); } Thread.Sleep(1); } strWorkingData = ""; return 0; } public void Send(string message) { DispatchMessage(message); // , DispatchMessage("\r
"); } #endregion /// <summary> /// /// </summary> public string SessionLog { get { return strFullLog; } } //====================================================================================== /// <summary> /// , 。 /// , GB2312 。 /// </summary> /// <param name="str_origin"> </param> /// <returns> </returns> private string ConvertToGB2312(string str_origin) { char[] chars = str_origin.ToCharArray(); byte[] bytes = new byte[chars.Length]; for (int i = 0; i < chars.Length; i++) { int c = (int)chars[i]; bytes[i] = (byte)c; } Encoding Encoding_GB2312 = Encoding.GetEncoding("GB2312"); string str_converted = Encoding_GB2312.GetString(bytes); return str_converted; } }
 
実行端telnet制御は大体この意味で、試してみると効果的で安定しています
-----------------------------------------------
  
 Telnet p = null;

private void DoTelnet(string port, string order)           //          (   )
        {
            if (String.IsNullOrEmpty(port) || String.IsNullOrEmpty(order))
            {
                textBox1.Text += "    -----" + DateTime.Now.ToString() + "\r
"; } else if (prv_port == port&& prv_order == order) // { textBox1.Text += " -----" + DateTime.Now.ToString() + "\r
"; } else { while (p == null || p.Connect() == false) { textBox1.Text += " , -----" + DateTime.Now.ToString() + "\r
"; p = new Telnet(" ip ", 23, 30); } // p.WaitFor("Username:"); p.Send(" "); p.WaitFor("Password:"); p.Send(" "); p.WaitFor("router01#"); p.Send("telnet ip"); p.WaitFor("Password:"); p.Send(" "); p.WaitFor("switch01>"); p.Send("en"); p.WaitFor("Password:"); p.Send(" enable "); p.WaitFor("switch01#"); p.Send("config t"); p.WaitFor("switch01(config)#"); string s = "int gigabitEthernet " + port; p.Send(s); s = "switch01(config-if-GigabitEthernet " +port+ ")#"; p.WaitFor(s); if (order == "open") { p.Send("no shutdown"); } else { p.Send("shutdown"); } p.Send("exit"); p.Send("exit"); p.Send("exit"); p.Send("quit"); prv_port= port; prv_order = order; textBox1.Text += port + ":" + order + " -----" + DateTime.Now.ToString() + "\r
"; } }