Advertisement
Guest User

Untitled

a guest
May 23rd, 2016
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.10 KB | None | 0 0
  1. public class Telnet
  2. {
  3. private IPEndPoint iep;
  4. private string address;
  5. private int port;
  6. private int timeout;
  7. private Socket s;
  8. Byte[] m_byBuff = new Byte[32767];
  9. private string strWorkingData = ""; // Holds everything received from the server since our last processing
  10. private string strFullLog = "";
  11. public Telnet(string Address, int Port, int CommandTimeout)
  12. {
  13. address = Address;
  14. port = Port;
  15. timeout = CommandTimeout;
  16. }
  17.  
  18.  
  19. private void OnRecievedData(IAsyncResult ar)
  20. {
  21. // Get The connection socket from the callback
  22. Socket sock = (Socket)ar.AsyncState;
  23.  
  24. // Get The data , if any
  25. int nBytesRec = sock.EndReceive(ar);
  26.  
  27. if (nBytesRec > 0)
  28. {
  29. // Decode the received data
  30. string sRecieved = CleanDisplay(Encoding.ASCII.GetString(m_byBuff, 0, nBytesRec));
  31.  
  32. // Write out the data
  33. if (sRecieved.IndexOf("[c") != -1) Negotiate(1);
  34. if (sRecieved.IndexOf("[6n") != -1) Negotiate(2);
  35.  
  36. // Console.WriteLine(sRecieved);
  37. strWorkingData += sRecieved;
  38. strFullLog += sRecieved;
  39.  
  40. // Launch another callback to listen for data
  41. AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
  42. sock.BeginReceive(m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, sock);
  43.  
  44. }
  45. else
  46. {
  47. // If no data was recieved then the connection is probably dead
  48. Console.WriteLine("Disconnected", sock.RemoteEndPoint);
  49. sock.Shutdown(SocketShutdown.Both);
  50. sock.Close();
  51. //Application.Exit();
  52. }
  53. }
  54.  
  55. private void DoSend(string strText)
  56. {
  57. try
  58. {
  59. Byte[] smk = new Byte[strText.Length];
  60. for (int i = 0; i < strText.Length; i++)
  61. {
  62. Byte ss = Convert.ToByte(strText[i]);
  63. smk[i] = ss;
  64. }
  65.  
  66. s.Send(smk, 0, smk.Length, SocketFlags.None);
  67. }
  68. catch (Exception ers)
  69. {
  70. Console.Error.WriteLine(ers.ToString());
  71. //MessageBox.Show("ERROR IN RESPOND OPTIONS");
  72. }
  73. }
  74.  
  75. private void Negotiate(int WhichPart)
  76. {
  77. StringBuilder x;
  78. string neg;
  79. if (WhichPart == 1)
  80. {
  81. x = new StringBuilder();
  82. x.Append((char)27);
  83. x.Append((char)91);
  84. x.Append((char)63);
  85. x.Append((char)49);
  86. x.Append((char)59);
  87. x.Append((char)50);
  88. x.Append((char)99);
  89. neg = x.ToString();
  90. }
  91. else
  92. {
  93.  
  94. x = new StringBuilder();
  95. x.Append((char)27);
  96. x.Append((char)91);
  97. x.Append((char)50);
  98. x.Append((char)52);
  99. x.Append((char)59);
  100. x.Append((char)56);
  101. x.Append((char)48);
  102. x.Append((char)82);
  103. neg = x.ToString();
  104. }
  105. SendMessage(neg, true);
  106. }
  107.  
  108. private string CleanDisplay(string input)
  109. {
  110. return input;
  111. }
  112.  
  113. /// <summary>
  114. /// Connects to the telnet server.
  115. /// </summary>
  116. /// <returns>True upon connection, False if connection fails</returns>
  117. public bool Connect()
  118. {
  119. IPHostEntry IPHost = Dns.Resolve(address);
  120. string[] aliases = IPHost.Aliases;
  121. IPAddress[] addr = IPHost.AddressList;
  122.  
  123. try
  124. {
  125. // Try a blocking connection to the server
  126. s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  127. iep = new IPEndPoint(addr[0], port);
  128. s.Connect(iep);
  129.  
  130. // If the connect worked, setup a callback to start listening for incoming data
  131. AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
  132. s.BeginReceive(m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, s);
  133.  
  134. // All is good
  135. return true;
  136. }
  137. catch (Exception)
  138. {
  139. // Something failed
  140. return false;
  141. }
  142.  
  143. }
  144.  
  145.  
  146. public void Disconnect()
  147. {
  148. if (s.Connected) s.Close();
  149. }
  150.  
  151. /// <summary>
  152. /// Waits for a specific string to be found in the stream from the server
  153. /// </summary>
  154. /// <param name="DataToWaitFor">The string to wait for</param>
  155. /// <returns>Always returns 0 once the string has been found</returns>
  156. public int WaitFor(string DataToWaitFor)
  157. {
  158. // Get the starting time
  159. long lngStart = DateTime.Now.AddSeconds(this.timeout).Ticks;
  160. long lngCurTime = 0;
  161.  
  162. while (strWorkingData.ToLower().IndexOf(DataToWaitFor.ToLower()) == -1)
  163. {
  164. // Timeout logic
  165. lngCurTime = DateTime.Now.Ticks;
  166. if (lngCurTime > lngStart)
  167. {
  168. throw new Exception("Timed Out waiting for : " + DataToWaitFor);
  169. }
  170. Thread.Sleep(1);
  171. }
  172. strWorkingData = "";
  173. return 0;
  174. }
  175.  
  176.  
  177. /// <summary>
  178. /// Waits for one of several possible strings to be found in the stream from the server
  179. /// </summary>
  180. /// <param name="DataToWaitFor">A delimited list of strings to wait for</param>
  181. /// <param name="BreakCharacters">The character to break the delimited string with</param>
  182. /// <returns>The index (zero based) of the value in the delimited list which was matched</returns>
  183. public int WaitFor(string DataToWaitFor, string BreakCharacter)
  184. {
  185. // Get the starting time
  186. long lngStart = DateTime.Now.AddSeconds(this.timeout).Ticks;
  187. long lngCurTime = 0;
  188.  
  189. string[] Breaks = DataToWaitFor.Split(BreakCharacter.ToCharArray());
  190. int intReturn = -1;
  191.  
  192. while (intReturn == -1)
  193. {
  194. // Timeout logic
  195. lngCurTime = DateTime.Now.Ticks;
  196. if (lngCurTime > lngStart)
  197. {
  198. throw new Exception("Timed Out waiting for : " + DataToWaitFor);
  199. }
  200.  
  201. Thread.Sleep(1);
  202. for (int i = 0; i < Breaks.Length; i++)
  203. {
  204. if (strWorkingData.ToLower().IndexOf(Breaks[i].ToLower()) != -1)
  205. {
  206. intReturn = i;
  207. }
  208. }
  209. }
  210. return intReturn;
  211.  
  212. }
  213.  
  214.  
  215. /// <summary>
  216. /// Sends a message to the server
  217. /// </summary>
  218. /// <param name="Message">The message to send to the server</param>
  219. /// <param name="SuppressCarriageReturn">True if you do not want to end the message with a carriage return</param>
  220. public void SendMessage(string Message, bool SuppressCarriageReturn)
  221. {
  222. strFullLog += "rnSENDING DATA ====> " + Message.ToUpper() + "rn";
  223. // Console.WriteLine("SENDING DATA ====> " + Message.ToUpper());
  224.  
  225. if (!SuppressCarriageReturn)
  226. {
  227. DoSend(Message + "r");
  228. }
  229. else
  230. {
  231. DoSend(Message);
  232. }
  233. }
  234.  
  235.  
  236. /// <summary>
  237. /// Sends a message to the server, automatically appending a carriage return to it
  238. /// </summary>
  239. /// <param name="Message">The message to send to the server</param>
  240. public void SendMessage(string Message)
  241. {
  242. strFullLog += "rnSENDING DATA ====> " + Message.ToUpper() + "rn";
  243. // Console.WriteLine("SENDING DATA ====> " + Message.ToUpper());
  244.  
  245. DoSend(Message + "r");
  246. }
  247.  
  248.  
  249. /// <summary>
  250. /// Waits for a specific string to be found in the stream from the server.
  251. /// Once that string is found, sends a message to the server
  252. /// </summary>
  253. /// <param name="WaitFor">The string to be found in the server stream</param>
  254. /// <param name="Message">The message to send to the server</param>
  255. /// <returns>Returns true once the string has been found, and the message has been sent</returns>
  256. public bool WaitAndSend(string WaitFor, string Message)
  257. {
  258. this.WaitFor(WaitFor);
  259. SendMessage(Message);
  260. return true;
  261. }
  262.  
  263.  
  264. /// <summary>
  265. /// Sends a message to the server, and waits until the designated
  266. /// response is received
  267. /// </summary>
  268. /// <param name="Message">The message to send to the server</param>
  269. /// <param name="WaitFor">The response to wait for</param>
  270. /// <returns>True if the process was successful</returns>
  271. public int SendAndWait(string Message, string WaitFor)
  272. {
  273. SendMessage(Message);
  274. this.WaitFor(WaitFor);
  275. return 0;
  276. }
  277.  
  278. public int SendAndWait(string Message, string WaitFor, string BreakCharacter)
  279. {
  280. SendMessage(Message);
  281. int t = this.WaitFor(WaitFor, BreakCharacter);
  282. return t;
  283. }
  284.  
  285.  
  286. /// <summary>
  287. /// A full log of session activity
  288. /// </summary>
  289. public string SessionLog
  290. {
  291. get
  292. {
  293. return strFullLog;
  294. }
  295. }
  296.  
  297.  
  298. /// <summary>
  299. /// Clears all data in the session log
  300. /// </summary>
  301. public void ClearSessionLog()
  302. {
  303. strFullLog = "";
  304. }
  305.  
  306.  
  307. /// <summary>
  308. /// Searches for two strings in the session log, and if both are found, returns
  309. /// all the data between them.
  310. /// </summary>
  311. /// <param name="StartingString">The first string to find</param>
  312. /// <param name="EndingString">The second string to find</param>
  313. /// <param name="ReturnIfNotFound">The string to be returned if a match is not found</param>
  314. /// <returns>All the data between the end of the starting string and the beginning of the end string</returns>
  315. public string FindStringBetween(string StartingString, string EndingString, string ReturnIfNotFound)
  316. {
  317. int intStart;
  318. int intEnd;
  319.  
  320. intStart = strFullLog.ToLower().IndexOf(StartingString.ToLower());
  321. if (intStart == -1)
  322. {
  323. return ReturnIfNotFound;
  324. }
  325. intStart += StartingString.Length;
  326.  
  327. intEnd = strFullLog.ToLower().IndexOf(EndingString.ToLower(), intStart);
  328.  
  329. if (intEnd == -1)
  330. {
  331. // The string was not found
  332. return ReturnIfNotFound;
  333. }
  334.  
  335. // The string was found, let's clean it up and return it
  336. return strFullLog.Substring(intStart, intEnd - intStart).Trim();
  337. }
  338.  
  339.  
  340. }
  341.  
  342. namespace ConsoleApplication1
  343. {
  344. class Program
  345. {
  346. static void Main(string[] args)
  347. {
  348. CiscoNoEnable cNE = new CiscoNoEnable();
  349. cNE.sHostName = "172.22.5.143";
  350. cNE.sUsername = "Eyespot@123";
  351. cNE.sPassword = "eyespot@123";
  352. cNE.getConfig();
  353. }
  354. }
  355. public class CiscoNoEnable
  356. {
  357.  
  358. public string sHostName;
  359. public string sUsername;
  360. public string sPassword;
  361.  
  362. private void Initialize_Components()
  363. {
  364. sHostName = "";
  365. sUsername = "";
  366. sPassword = "";
  367. }
  368.  
  369. public CiscoNoEnable()
  370. {
  371. Initialize_Components();
  372. }
  373. public void getConfig()
  374. {
  375.  
  376. this.sHostName = this.sHostName.Trim();
  377. this.sUsername = this.sUsername.Trim();
  378. this.sPassword = this.sPassword.Trim();
  379.  
  380. RafiTEL.Telnet mST = new RafiTEL.Telnet(this.sHostName, 23, 8);
  381.  
  382. if (mST.Connect() == false)
  383. {
  384. Console.WriteLine("");
  385. Console.WriteLine("Error: ");
  386. Console.WriteLine("Timeout connecting to: " + this.sHostName);
  387. Console.WriteLine("");
  388. }
  389. else
  390. {
  391. try
  392. {
  393. mST.WaitFor("Username:");
  394. }
  395. catch (Exception exc)
  396. {
  397. Console.WriteLine(exc.Message);
  398. }
  399. mST.SendMessage(this.sUsername);
  400. mST.WaitFor("Password:");
  401. mST.SendMessage(this.sPassword);
  402. mST.WaitFor("#");
  403. mST.SendMessage("term len 0");
  404. mST.WaitFor("#");
  405. mST.SendMessage("show run");
  406. mST.WaitFor("#");
  407. mST.SendMessage("exit");
  408. Console.Write(mST.FindStringBetween("bytesrn", "rnrn", "Error: Configuration not obtained"));
  409. }
  410. }
  411. }
  412. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement