public EthernetSwitch Send(EthernetSwitch ethernetDevice, Dictionary <string, string> SettingsDict) { _sDict = SettingsDict; ShellStream stream = _sshClient.CreateShellStream("", 0, 0, 0, 0, 0); stream.WriteLine("sh system id"); GetIDoverSSH(GetDeviceResponse(stream), ethernetDevice); stream.WriteLine("en"); stream.WriteLine(_sDict["NewAdminPassword"]); stream.WriteLine("conf t"); stream.WriteLine("no ip telnet server"); stream.WriteLine("exit"); stream.WriteLine("wr mem"); #if DEBUG stream.WriteLine("N"); #endif #if !DEBUG stream.WriteLine("Y"); #endif GetDeviceResponse(stream); stream.Close(); return(ethernetDevice); }
private Dictionary <string, string> GetPrintingDict(EthernetSwitch ethSwitch) { Dictionary <string, string> printDict = new Dictionary <string, string>(); printDict.Add("ITextObjectIPaddress", ethSwitch.AddressIP); printDict.Add("ITextObjectDesignation", ethSwitch.Designation); printDict.Add("ITextObjectMask", ethSwitch.Netmask.ToString());; printDict.Add("ITextObjectSerial", ethSwitch.Serial); return(printDict); }
public EthernetSwitch Send(EthernetSwitch ethernetDevice, Dictionary <string, string> SettingsDict) { _sDict = SettingsDict; _ethernetDevice = ethernetDevice; PacketSendToTelnet(); // Передаём настройки по Telnet-протоколу _tc.ConnectionClose(); // Закрываем Telnet-соединение return(ethernetDevice); // Возвращаем объект с заполненными свойствами полученными из коммутатора }
private void GetIDoverSSH(string strForParse, EthernetSwitch ethernetDevice) { string answer = strForParse; string MACaddress; string HardwareVersion; string SerialNumber; if (answer.Contains("MAC address :")) { answer = answer.Remove(0, answer.IndexOf("MAC address :")); answer = answer.Replace(" ", ""); //"MACaddress:e0:d9:e3:3d:ca:80Hardwareversion:01.03.01Serialnumber:ES50004388" MACaddress = answer.Substring(answer.IndexOf(":") + 1, 17); answer = answer.Remove(0, answer.IndexOf("Hardwareversion:")); //"Hardwareversion:01.03.01Serialnumber:ES50004388" HardwareVersion = answer.Substring(answer.IndexOf(":") + 1, answer.IndexOf("Serialnumber:") - (answer.IndexOf(":") + 1)); answer = answer.Remove(0, answer.IndexOf("Serialnumber:")); //"Serialnumber:ES50004388" SerialNumber = answer.Remove(0, answer.IndexOf(":") + 1); } else { answer = answer.Trim(); //"\rSWITCH_1_2>sh system id\rUnit MAC address Hardware version Serial number ---- ----------------- ---------------- ------------- 1 e8:28:c1:5d:5f:60 01.02.01 ES5E004602" int LastWordIndex = answer.LastIndexOf(' ') + 1; SerialNumber = answer.Substring(LastWordIndex, answer.Length - LastWordIndex); answer = answer.Remove(LastWordIndex); answer = answer.Trim(); // //"\rSWITCH_1_2>sh system id\rUnit MAC address Hardware version Serial number ---- ----------------- ---------------- ------------- 1 e8:28:c1:5d:5f:60 01.02.01" LastWordIndex = answer.LastIndexOf(' ') + 1; HardwareVersion = answer.Substring(LastWordIndex, answer.Length - LastWordIndex); answer = answer.Remove(LastWordIndex); answer = answer.Trim(); // //"\rSWITCH_1_2>sh system id\rUnit MAC address Hardware version Serial number ---- ----------------- ---------------- ------------- 1 e8:28:c1:5d:5f:60" LastWordIndex = answer.LastIndexOf(' ') + 1; MACaddress = answer.Substring(LastWordIndex, answer.Length - LastWordIndex); } ethernetDevice.MACaddress = MACaddress; ethernetDevice.HardwareVersion = HardwareVersion; ethernetDevice.Serial = SerialNumber; ethernetDevice.Username = _sDict["NewAdminLogin"]; ethernetDevice.Password = _sDict["NewAdminPassword"]; }
protected virtual async Task Main() { Log.SetLevel(Log.Level.TRACE, Log.Groups.SHOW); Vlan.Register(1, "DEFAULT"); Global.SetDeviceAutoStartup(true); //Global.SetPortAutoInit(true); /* * PC1 --- eth0/1 * | * | fa0/1 * SW1 * | fa0/2 * | * | fa0/1 * SW2 * | fa0/1 * | * PC2 --- eth0/1 */ Log.Group("Initialize devices"); var pc1 = new EthernetDevice("pc1"); var pc2 = new EthernetDevice("pc2"); var sw1 = new EthernetSwitch("sw1"); var sw2 = new EthernetSwitch("sw2"); Log.Group("Initialize ports"); //pc ports pc1[ETH01].Init(); pc2[ETH01].Init(); //Connection from sw1 to pc1 sw1[FA01].Init(); //Connection from sw2 to pc2 sw2[FA01].Init(); //Connection from sw1 to sw2 sw1[FA02].Init(); sw2[FA02].Init(); Log.Group("Connect ports"); //Connect the pcs to the switches pc1[ETH01].ConnectTo(sw1[FA01]); pc2[ETH01].ConnectTo(sw2[FA01]); //Connect the switches to each other sw1[FA02].ConnectTo(sw2[FA02]); Log.Group("Set switchport modes"); //Set the ports from pc to switch to access vlan 1 sw1.SetPort(FA01, EthernetSwitch.AccessMode.ACCESS, Vlan.Get(1)); sw2.SetPort(FA01, EthernetSwitch.AccessMode.ACCESS, Vlan.Get(1)); //Set the ports from switch to switch to trunk sw1.SetPort(FA02, EthernetSwitch.AccessMode.TRUNK, null); sw2.SetPort(FA02, EthernetSwitch.AccessMode.TRUNK, null); //Log.Group("Current state"); //Log.PrintState(); //Learn MAC Addresses Log.Group("Learn MAC Addresses"); /* * The API can be used with constructors (like this) */ pc1[ETH01].SendSync(new EthernetFrame(Constants.ETHERNET_BROADCAST_PORT, pc1[ETH01], Vlan.Get(1), new RawPacket(new byte[100]))); //Wait for all sending operations to be finished (you don't HAVE to wait...I just prefer doing so, cause the log is more readable) //This is necessary cause even tho you send this frame synchronously, all the connected devices create new tasks for incoming frames await Global.WaitForOperationsFinished(); /* * Or like this (with a static methods and a scapy-esque construction method) */ pc2[ETH01].SendSync(Ethernet(Constants.ETHERNET_BROADCAST_ADDRESS, pc2[ETH01]) < -/*Yes...this is indeed valid C#*/ Dot1Q(Vlan.Get(1)) < -RawPacket(new byte[100])); await Global.WaitForOperationsFinished(); Log.Group("Send Ethernet frame over learned ports"); pc1[ETH01].SendAsync(Ethernet(pc2[ETH01], pc1[ETH01]) | Dot1Q(Vlan.Get(1)) | RawPacket(new byte[100])); await Global.WaitForOperationsFinished(); pc1[ETH01].Disconnect(); pc2[ETH01].Disconnect(); pc1.Shutdown(); pc2.Shutdown(); Log.PrintState(); //Console.ReadKey(); }
public bool UploadConfigStateMachine(EthernetSwitch switchDevice, Dictionary <string, string> settings, CancellationToken token) { MessageToConsole("Waiting device..."); Dictionary <string, string> _sDict = settings; int State = 0; bool IsSendComplete = false; while (State < 6 && !token.IsCancellationRequested) { switch (State) { case 0: // Пингуем в цикле коммутатор по дефолтному адресу пока коммутатор не ответит на пинг MessageForUser("Ожидание" + "\r\n" + "коммутатора"); if (SendMultiplePing(_sDict["DefaultIPAddress"], repitNumer)) { State = 1; } break; case 1: // Пытаемся в цикле подключиться по Telnet (сервер Telnet загружается через некоторое время после успешного пинга) if (_telnetSender.CreateConnection(_sDict["DefaultIPAddress"], _telnetPort, _sDict["DefaultAdminLogin"], _sDict["DefaultAdminPassword"], null)) { State = 2; } break; case 2: // Заливаем первую часть конфига в коммутатор по Telnet MessageToConsole("Заливаем первую часть конфига в коммутатор по Telnet."); _telnetSender.Send(switchDevice, _sDict); // Закрываем Telnet соединение _telnetSender.CloseConnection(); State = 3; break; case 3: // Пытаемся в цикле подключиться к SSH-серверу if (_sshSender.CreateConnection(switchDevice.AddressIP, _sshPort, _sDict["NewAdminLogin"], _sDict["NewAdminPassword"], RSAfile)) { State = 4; } break; case 4: // Заливаем вторую часть конфига по SSH-протоколу MessageToConsole("Заливаем вторую часть конфига по SSH-протоколу."); _sshSender.Send(switchDevice, _sDict); // Закрываем SSH-соединение _sshSender.CloseConnection(); MessageToConsole("Заливка конфига в коммутатор завершена."); State = 5; break; case 5: // Пингуем в цикле коммутатор по новому IP-адресу (как только пинг пропал - коммутатор отключили) MessageForUser("Замени" + "\r\n" + "коммутатор!"); if (!SendMultiplePing(switchDevice.AddressIP, repitNumer)) { State = 6; } break; case 6: IsSendComplete = true; break; default: break; } Thread.Sleep(100); // Слишком часто коммутатор лучше не долбить (может воспринять как атаку) // Go to state 0 } return(IsSendComplete); }