How To Simulate Telnet Session in Java Как смоделировать Telnet сессии в Java
Often we come across procedures which need to be performed by issuing commands in a telnet session. Нередко нам приходилось сталкиваться процедур, которые должны быть выполнены путем выдачи команды в telnet сессии. It is relatively easy to do it manually but is definitely not suitable for automation. Это сравнительно легко сделать это вручную, но, безусловно, не подходит для автоматизации. Let’s see how you can easily automate such tasks using Java software. Давайте посмотрим, как можно легко автоматизировать выполнение таких задач, используя программное обеспечение Java. Sample code included. Пример кода включен.
Here is the core code: Вот основной код:
// Conversation; Simulating telnet session with James server / / Переписка; Симуляция telnet сессию с Джеймсом сервера
readLines(r, 3); readLines (р, 3);
writeLine(w, login); writeLine (ж, вход);
readLines(r, 1); readLines (р, 1);
writeLine(w, password); writeLine (ж, пароль);
readLines(r, 1); readLines (р, 1);
writeLine(w, SHUTDOWN); writeLine (ж, shutdown);
readLines(r, 1); readLines (р, 1);
readLines() reads and discards specified number of lines (response). readLines () считывает и выброса определенного числа линий (ответ).
Here are the key functions: Вот основные функции:
/** Read and discard count lines from BufferedReader r */ public static void readLines(BufferedReader r, int count) throws IOException { for(int i = 0;i < count;i++) { String t = r.readLine(); if(DEBUG) System.out.println(t); } } /** Write out to BufferedWriter w and flush */ public static void writeLine(BufferedWriter w, String out) throws IOException { w.write(out + CRLF, 0, (out + CRLF).length()); w.flush(); } / ** Прочтите и отказаться от подсчета строки из BufferedReader р * / государственного статического недействительным readLines (BufferedReader р, int кол) броски IOException (для (int я = 0; я <кол; я + +) (String т = r.readLine (); если (DEBUG) System.out.println (т);)) / ** Записать на BufferedWriter ж и промойте * общественности статических недействительным writeLine (BufferedWriter ж, из String) броски IOException (w.write (из + CRLF, 0 , (Из + CRLF). Длины ()); w.flush ();) You can download the code Вы можете загрузить код here здесь . It is used to shutdown Apache James Mail Server. Он используется для остановки Apache Джеймс Mail Server. The utility is fully described along with the options in - Утилита полностью описаны наряду с варианты -- Shutdown Apache James Mail Server - Java Utility Завершение Apache Джеймс Mail Server - Java Utility
Filed under Поданного в соответствии с Headline News Headline News , How To Как , Java Software Программное обеспечение Java , Tech Note Технология Примечание | |
| |
RSS 2.0 RSS 2,0 | |
Email this Article Отослать Статья
You may also like to read Вы можете также люблю читать |





April 17th, 2006 at 12:45 am 17 апреля 2006 года в 12:45 утра
good хороший
March 13th, 2008 at 10:59 pm 13 марта 2008 года в 10:59 вечера
Hey, Эй,
I have a question re the above code. У меня вопрос вновь выше код. I attempted to modify this for use with a Cisco Catalyst 3500 swtich to return the the mac address tale using the “sh mac-address-table” command. Я пытался изменить это для использования с Cisco Catalyst 3500 swtich вернуться МАС-адресу история с использованием "ш макинтош-адрес столом" команду. However, I’m having a problem where, using the above code, i need to specify the number of lines to read back. Тем не менее, у меня возникают проблемы, когда, используя вышеуказанный код, я необходимо указать количество строк читать обратно. But, depending on the amount of clients physically collected into the switch, the number varies. Но, в зависимости от количества клиентов физически, собранных в коммутаторе количество варьируется. I attempted to write a while((line = in.readLine()) != null) { .. Я попытался написать в то время как ((линия = in.readLine ())! Недействительными =) (.. } block of code but tis fails where, once it reaches the end, it sits there as if expecting more. ) Блока кода, но tis, не где, как только она доходила до конца, она сидит там, как будто ожидая более. It never receives a NULL at the end. Она никогда не получает NULL в конце.
In another attempt, i assumed the last line should contain a prompt. В одну попытку, я себя последняя строка должна содержать строки. However, this also failed. Тем не менее, это тоже не удалось. It seems readLine() discards prompts but should replace them with NULL. Кажется, readLine () рыбы подсказок, но следует заменить их NULL. But this doesn’t seem to be true for me. Но это вовсе не похоже чтобы быть правдой для меня.
My question is this, is there a way to adapt your code so that it can read an unknown number of lines and store the output? Мой вопрос заключается в этом, есть способ адаптировать свой код так, что она умеет читать неизвестное число строк и хранения продукции?
Many Thanks, Большое спасибо,
A Неопределенный артикль