[image]

Вопрос про паскаль: как выполнить команду ping?

 
+
-
edit
 

Mishka

модератор
★★★
Mishka>> Да ты, брат, заплутал в трёх соснах. :F Посмотри сюда — Вопрос про паскаль: как выполнить команду ping? [Mishka#27.08.08 16:48]
Kernel3> Ну и? Вот здесь где Паскаль?
Это демонстрация того, что возвращает код. И в этом примере про анализ кода от commnd.com не идёт и речи.
   
+
-
edit
 

Kernel3

аксакал

Mishka> Это демонстрация того, что возвращает код. И в этом примере про анализ кода от commnd.com не идёт и речи.
Ага. Вот только для Паскаля это не подходит. И я написал, почему.
   
+
-
edit
 

Mishka

модератор
★★★
Mishka>> Это демонстрация того, что возвращает код. И в этом примере про анализ кода от commnd.com не идёт и речи.
Kernel3> Ага. Вот только для Паскаля это не подходит. И я написал, почему.
Ы? Анализируй код в том примере, что я дал точно таким же образом. А скриптик — демонстратор, что ping возвращает код.
   
RU Тихон #27.08.2008 20:06
+
-
edit
 

Тихон

опытный

Ну так как я понимаю, необязательно брать результат непосредственно из выполненной команды.
Можно этой же моей программой потом его выдрать из сформированного файла.
   
+
-
edit
 

Kernel3

аксакал

Mishka> Ы? Анализируй код в том примере, что я дал точно таким же образом. А скриптик — демонстратор, что ping возвращает код.
Бл@. Аа. При прямом вызове ping.exe будет работать, канешн.
   
US Mishka #28.08.2008 02:17  @Тихон#27.08.2008 20:06
+
-
edit
 

Mishka

модератор
★★★
Тихон> Ну так как я понимаю, необязательно брать результат непосредственно из выполненной команды.
Тихон> Можно этой же моей программой потом его выдрать из сформированного файла.
Можно, только формат файлика будет не статический. :) Количество строк будет варьироваться в зависимости от ошибок, длина строк тоже.

code text
  1.  
  2. E:\t>ping www.yaho.com
  3.  
  4. Pinging rc.yahoo.akadns.net [206.190.60.37] with 32 bytes of data:
  5.  
  6. Reply from 206.190.60.37: bytes=32 time=156ms TTL=252
  7. Reply from 206.190.60.37: bytes=32 time=127ms TTL=252
  8. Reply from 206.190.60.37: bytes=32 time=174ms TTL=252
  9. Reply from 206.190.60.37: bytes=32 time=198ms TTL=252
  10.  
  11. Ping statistics for 206.190.60.37:
  12.     Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
  13. Approximate round trip times in milli-seconds:
  14.     Minimum = 127ms, Maximum = 198ms, Average = 163ms
  15.  
  16. E:\t>ping www.yah.com
  17.  
  18. Pinging yah.com [72.165.196.114] with 32 bytes of data:
  19.  
  20. Reply from 72.165.196.114: bytes=32 time=144ms TTL=252
  21. Reply from 72.165.196.114: bytes=32 time=204ms TTL=252
  22. Reply from 72.165.196.114: bytes=32 time=154ms TTL=252
  23. Reply from 72.165.196.114: bytes=32 time=231ms TTL=252
  24.  
  25. Ping statistics for 72.165.196.114:
  26.     Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
  27. Approximate round trip times in milli-seconds:
  28.     Minimum = 144ms, Maximum = 231ms, Average = 183ms
  29.  
  30. E:\t>ping www.yahf.com
  31.  
  32. Pinging www.yahf.com [82.98.86.173] with 32 bytes of data:
  33.  
  34. Reply from 82.98.86.173: bytes=32 time=260ms TTL=253
  35. Reply from 82.98.86.173: bytes=32 time=203ms TTL=253
  36. Reply from 82.98.86.173: bytes=32 time=254ms TTL=253
  37. Reply from 82.98.86.173: bytes=32 time=249ms TTL=253
  38.  
  39. Ping statistics for 82.98.86.173:
  40.     Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
  41. Approximate round trip times in milli-seconds:
  42.     Minimum = 203ms, Maximum = 260ms, Average = 241ms
  43.  
  44. E:\t>ping www.yahf1.com
  45. Ping request could not find host www.yahf1.com. Please check the name and try again.
  46.  
  47. E:\t>ping everest
  48.  
  49. Pinging everest.ca.com [138.42.176.156] with 32 bytes of data:
  50.  
  51. Reply from 138.42.176.156: bytes=32 time=2ms TTL=63
  52. Reply from 138.42.176.156: bytes=32 time<1ms TTL=63
  53. Reply from 138.42.176.156: bytes=32 time<1ms TTL=63
  54. Reply from 138.42.176.156: bytes=32 time<1ms TTL=63
  55.  
  56. Ping statistics for 138.42.176.156:
  57.     Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
  58. Approximate round trip times in milli-seconds:
  59.     Minimum = 0ms, Maximum = 2ms, Average = 0ms
  60.  
  61. E:\t\Nuno>ping lenta.ru
  62.  
  63. Pinging lenta.ru [81.19.69.232] with 32 bytes of data:
  64.  
  65. Reply from 81.19.69.232: bytes=32 time=315ms TTL=253
  66. Reply from 81.19.69.232: bytes=32 time=311ms TTL=253
  67. Reply from 81.19.69.232: bytes=32 time=343ms TTL=253
  68. Reply from 81.19.69.232: bytes=32 time=271ms TTL=253
  69.  
  70. Ping statistics for 81.19.69.232:
  71.     Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
  72. Approximate round trip times in milli-seconds:
  73.     Minimum = 271ms, Maximum = 343ms, Average = 310ms
  74.  
  75.  
  76.  
  77. E:\t>ping lenta.ru
  78.  
  79. Pinging lenta.ru [81.19.69.232] with 32 bytes of data:
  80.  
  81. Request timed out.
  82. Reply from 81.19.69.232: bytes=32 time=323ms TTL=253
  83. Reply from 81.19.69.232: bytes=32 time=298ms TTL=253
  84. Reply from 81.19.69.232: bytes=32 time=407ms TTL=253
  85.  
  86. Ping statistics for 81.19.69.232:
  87.     Packets: Sent = 4, Received = 3, Lost = 1 (25% loss),
  88. Approximate round trip times in milli-seconds:
  89.     Minimum = 298ms, Maximum = 407ms, Average = 342ms

Вот тебе несколько примеров. Там ещё нет кучки, когда идут сообщения по ICMP. Дерзай, анализируй.
   
RU Тихон #28.08.2008 16:08  @Mishka#27.08.2008 16:48
+
-
edit
 

Тихон

опытный

Тихон>> ОГРОМНОЕ СПАСИБО!!!
Тихон>> Работает!
Тихон>> Волшебство прям. Шайтан машина компьютер, однако.
Mishka> Только объясни мне, как ты будешь проверять результаты пингования? :F

Мишка, твой пример с прямым вызовом ping.exe не работает - ругается unknown identfier на exec.
   
+
-
edit
 

au

   
★★
Тихон> Мишка, твой пример с прямым вызовом ping.exe не работает - ругается unknown identfier на exec.

Путь пробит к пингу.ехе? Или пишите полный путь в вызове (C:\123\345\ping.exe).
   
+
-
edit
 

Vale

Сальсолёт
★☆
Тихон, код процедуры следует засовывать под спойлер, если хочется помощи.
"По фотографии не лечим"
А так - у тебя Ехес - латиницей написан? :F Потому что это сообщение компилятора означает что оно не поняло чего-то в этой строчке.
Приведи здесь хотя бы строчку с вызовом exec.
   
Это сообщение редактировалось 28.08.2008 в 17:03
RU Спокойный_Тип #28.08.2008 17:11  @Vale#28.08.2008 16:54
+
-
edit
 
может перл можно както из паскаля вызывать? там либ полно сетевых
   
RU Alexandrc #28.08.2008 18:10  @спокойный тип#28.08.2008 17:11
+
-
edit
 

Alexandrc

аксакал

Для делфи вот такое есть

code text
  1.    1. unit Unit1;  
  2.    2.  
  3.    3. interface  
  4.    4.  
  5.    5. uses  
  6.    6.   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,  
  7.    7.   Dialogs, StdCtrls, IdBaseComponent, IdComponent, IdRawBase, IdRawClient,  
  8.    8.   IdIcmpClient;  
  9.    9.  
  10.   10. type  
  11.   11.   TForm1 = class(TForm)  
  12.   12.     icmp: TIdIcmpClient;  
  13.   13.     Button1: TButton;  
  14.   14.     procedure Button1Click(Sender: TObject);  
  15.   15.   private  
  16.   16.     { Private declarations }  
  17.   17.   public  
  18.   18.     { Public declarations }  
  19.   19.   end;  
  20.   20.  
  21.   21. var  
  22.   22.   Form1: TForm1;  
  23.   23.  
  24.   24. implementation  
  25.   25.  
  26.   26. {$R *.dfm}  
  27.   27.  
  28.   28. procedure TForm1.Button1Click(Sender: TObject);  
  29.   29. begin  
  30.   30. icmp.Host:='194.87.0.50';  
  31.   31. icmp.Ping();  
  32.   32. showmessage('Время до хоста: '+inttostr(icmp.ReplyStatus.MsRoundTripTime)+'ms');  
  33.   33. end;  
  34.   34.  
  35.   35. end.  
   
RU Тихон #29.08.2008 08:49
+
-
edit
 

Тихон

опытный

>>Путь пробит к пингу.ехе? Или пишите полный путь в вызове (C:\123\345\ping.exe).

>>Тихон, код процедуры следует засовывать под спойлер, если хочется помощи.
>>"По фотографии не лечим"
>>А так - у тебя Ехес - латиницей написан? :F Потому что это сообщение компилятора означает что оно не поняло чего-то в этой >>строчке.
>>Приведи здесь хотя бы строчку с вызовом exec.

Вот:

Var
the_command_line : string;
the_command_params : string;

begin
the_command_line:='c:\WINDOWS\system32\ping.exe';
the_command_params:='127.0.0.1';
Exec( the_command_line, the_command_params )
end.

Файл по этому пути есть. Exec написан латиницей.

Говорит Unknown identifier. Паскаль - досовский Турбо Паскаль.

Упд: Всё, понял сам. Надо же указать uses dos.
   
Это сообщение редактировалось 29.08.2008 в 08:56
RU Alexandrc #29.08.2008 10:46  @Тихон#29.08.2008 08:49
+
-
edit
 

Alexandrc

аксакал

Тихон> the_command_line:='c:\WINDOWS\system32\ping.exe';

Я бы использовал %systemroot%\system32\ping.exe
Мало ли на какой диск и в какую папку MS Win установлен ;)
   
+
-
edit
 

Mishka

модератор
★★★
Тихон>> the_command_line:='c:\WINDOWS\system32\ping.exe';
Alexandrc> Я бы использовал %systemroot%\system32\ping.exe
Alexandrc> Мало ли на какой диск и в какую папку MS Win установлен ;)
Его надо специально прочитать — чем-то вроде GetEnv. иначе не будет работать в моём варианте. Там должен быть указан путь, подстановки не производятся.
   

DSB

втянувшийся

au>> Забыли дос, да? :) Если "ping (..................) > output.txt", то вывод пинга будет в этот самый тхт.
Mishka> Тогда надо делать
Mishka> Чтобы и возможные сообщения об ошибках туда валились.

Впервые вижу такое чудо - "2>&1".... Где такое вычитал?
   

MIKLE

старожил

сзоф
вспомнилась война и написание эмулятора зрк+иап пво..
   
+
-
edit
 

DSB

втянувшийся

Тихон>>> ОГРОМНОЕ СПАСИБО!!!
Тихон> Тихон>> Работает!
Тихон> Тихон>> Волшебство прям. Шайтан машина компьютер, однако.
Mishka>> Только объясни мне, как ты будешь проверять результаты пингования? :F
Тихон> Да с помошью Гомо Сапиенса за компом. Я там состругал стрелочное меню с подменю, чел выбирает нужный пункт и видит результаты пинга.
Тихон> Хотя с радостью выслушаю предложения по автоматизации процесса!!!

Если надо, то могу помочь закодировать через VB Script (по крайней мере досовские окна не будут мелькать).
   

Mishka

модератор
★★★
au>>> Забыли дос, да? :) Если "ping (..................) > output.txt", то вывод пинга будет в этот самый тхт.
Mishka>> Тогда надо делать
Mishka>> Чтобы и возможные сообщения об ошибках туда валились.
DSB> Впервые вижу такое чудо - "2>&1".... Где такое вычитал?
Только настоящие люди понимают шеллы. :) Называется переназначение файлов. Пришло из UNIX-а. Ещё когда ДОС писали. Программа при старте получает сразу несколько открытых файлов. Нас интересуют первые три:
0 — stdin
1 — stdout
2 — stderr
Когда ты задаёшь переназначение, то должен указать какой файл ты переназначешь и как — на ввод или на вывод. 1 для вывода можно не указывать — это по умолчанию. Как и 0 для ввода. Но можно и указывать. А вот с 2 так не проходит. Это чудо называется переназначить вывод со stderr в тот же файли, что и 1 (stdout), т.е. сообщения об ошибках пойдут туда же, куда и стандартный вывод.

А так, зайди в Unix, выдай командочку man sh и ищи file redirection.
   

DSB

втянувшийся

DSB>> Впервые вижу такое чудо - "2>&1".... Где такое вычитал?
Mishka> Только настоящие люди понимают шеллы. :) Называется переназначение файлов. Пришло из UNIX-а. Ещё когда ДОС писали. Программа при старте получает сразу несколько открытых файлов. Нас интересуют первые три:
Mishka> 0 — stdin
Mishka> 1 — stdout
Mishka> 2 — stderr
Mishka> Когда ты задаёшь переназначение, то должен указать какой файл ты переназначешь и как — на ввод или на вывод. 1 для вывода можно не указывать — это по умолчанию. Как и 0 для ввода. Но можно и указывать. А вот с 2 так не проходит. Это чудо называется переназначить вывод со stderr в тот же файли, что и 1 (stdout), т.е. сообщения об ошибках пойдут туда же, куда и стандартный вывод.

Я понял. Раньше немало книг перечитал по DOS, но такой фичи не видал )))
Это вообще документировано?
   

Mishka

модератор
★★★
DSB> Я понял. Раньше немало книг перечитал по DOS, но такой фичи не видал )))

Ну, по правде сказать, в ДОС интрепретарор не всё умел. А вот в NT — уже получше.

DSB> Это вообще документировано?
Моя ХР на вопрос "file redirection" выдаёт:
code text
  1. Using command redirection operatorsYou can use redirection operators to redirect command input and output streams from the default locations to different locations. The input or output stream location is referred to as a handle.
  2.  
  3. The following table lists operators that you can use to redirect command input and output streams.
  4.  
  5. Redirection operator Description
  6. > Writes the command output to a file or a device, such as a printer, instead of the Command Prompt window.
  7. < Reads the command input from a file, instead of reading input from the keyboard.
  8. >> Appends the command output to the end of a file without deleting the information that is already in the file.
  9. >& Writes the output from one handle to the input of another handle.
  10. <& Reads the input from one handle and writes it to the output of another handle.
  11. | Reads the output from one command and writes it to the input of another command. Also known as a pipe.  
  12.  
  13. By default, you send the command input (that is, the STDIN handle) from your keyboard to Cmd.exe, and then Cmd.exe sends the command output (that is, the STDOUT handle) to the Command Prompt window.
  14.  
  15. The following table lists the available handles.
  16.  
  17. Handle Numeric equivalent of handle Description
  18. STDIN 0 Keyboard input
  19. STDOUT 1 Output to the Command Prompt window
  20. STDERR 2 Error output to the Command Prompt window
  21. UNDEFINED 3-9 These handles are defined individually by the application and are specific to each tool.
  22.  
  23. The numbers zero through nine (that is, 0-9) represent the first 10 handles. You can use Cmd.exe to run a program and redirect any of the first 10 handles for the program. To specify which handle you want to use, type the number of the handle before the redirection operator. If you do not define a handle, the default < redirection input operator is zero (0) and the default > redirection output operator is one (1). After you type the < or > operator, you must specify where you want to read or write the data. You can specify a file name or another existing handle.
  24.  
  25. To specify redirection to existing handles, use the ampersand (&) character followed by the handle number that you want to redirect (that is, &handle#). For example, the following command redirects handle 2 (that is, STDERR) into handle 1 (that is, STDOUT):
  26.  
  27. 1<&2
  28.  
  29. Duplicating handles
  30. The & redirection operator duplicates output or input from one specified handle to another specified handle. For example, to send dir output to File.txt and send the error output to File.txt, type:
  31.  
  32. dir>c:\file.txt 2>&1
  33.  
  34. When you duplicate a handle, you duplicate all characteristics of the original occurrence of the handle. For example, if a handle has write-only access, all duplicates of that handle have write-only access. You cannot duplicate a handle with read-only access into a handle with write-only access.
  35.  
  36. Redirecting command input (<)
  37. To redirect command input from the keyboard to a file or device, use the < operator. For example, to get the command input for the sort command from File.txt:
  38.  
  39. sort<file.txt
  40.  
  41. The contents of File.txt appear in the Command Prompt window as an alphabetized list.
  42.  
  43. The < operator opens the specified file name with read-only access. As a result, you cannot write to the file when you use this operator. For example, if you start a program with <&2, all attempts to read handle 0 fail because handle 2 is initially opened with write-only access.
  44.  
  45.  Note
  46.  
  47. Zero is the default handle for the < redirection input operator.
  48. Redirecting command output (>)
  49. Almost all commands send output to your Command Prompt window. Even commands that send output to a drive or printer display messages and prompts in the Command Prompt window.
  50.  
  51. To redirect command output from the Command Prompt window to a file or device, use the > operator. You can use this operator with most commands. For example, to redirect dir output to Dirlist.txt:
  52.  
  53. dir>dirlist.txt
  54.  
  55. If Dirlist.txt does not exist, Cmd.exe creates it. If Dirlist.txt exists, Cmd.exe replaces the information in the file with the output from the dir command.
  56.  
  57. To run the netsh routing dump command and then send the command output to Route.cfg, type:
  58.  
  59. netsh routing dump>c:\route.cfg
  60.  
  61. The > operator opens the specified file with write-only access. As a result, you cannot read the file when you use this operator. For example, if you start a program with redirection >&0, all attempts to write handle 1 fail because handle 0 is initially opened with read-only access.
  62.  
  63.  Note
  64.  
  65. One is the default handle for the > redirection output operator.
  66. Using the <& operator to redirect input and duplicate
  67. To use the redirection input operator <&, the file you specify must already exist. If the input file exists, Cmd.exe opens it as read-only and sends the characters contained in the file as input to the command as if they were input from the keyboard. If you specify a handle, Cmd.exe duplicates the handle you specify onto the existing handle in the system.
  68.  
  69. For example, to open File.txt as input read to handle 0 (that is, STDIN), type:
  70.  
  71. <file.txt
  72.  
  73. To open File.txt, sort the contents and then send the output to the Command Prompt window (that is, STDOUT), type:
  74.  
  75. sort<file.txt
  76.  
  77. To find File.txt, and then redirect handle 1 (that is, STDOUT) and handle 2 (that is, STDERR) to the Search.txt, type:
  78.  
  79. findfile file.txt>search.txt 2<&1
  80.  
  81. To duplicate a user-defined handle 3 as input read to handle 0 (that is, STDIN), type:
  82.  
  83. <&3
  84.  
  85. Using the >& operator to redirect output and duplicate
  86. If you redirect output to a file and you specify an existing file name, Cmd.exe opens the file as write-only and overwrites the file's contents. If you specify a handle, Cmd.exe duplicates the file onto the existing handle.
  87.  
  88. To duplicate a user-defined handle 3 into handle 1, type:
  89.  
  90. >&3
  91.  
  92. To redirect all of the output, including handle 2 (that is, STDERR), from the ipconfig command to handle 1 (that is, STDOUT), and then redirect the ouput to Output.log, type:
  93.  
  94. ipconfig.exe>>output.log 2>&1
  95.  
  96. Using the >> redirection operator to append output
  97. To add the output from a command to the end of a file without losing any of the information already in the file, use two consecutive greater than signs (that is, >>). For example, the following command appends the directory list produced by the dir command to the Dirlist.txt file:
  98.  
  99. dir>>dirlist.txt
  100.  
  101. To append the output of the netstat command to the end of Tcpinfo.txt, type:
  102.  
  103. netstat>>tcpinfo.txt
  104.  
  105. Using the pipe operator (|)
  106. The pipe operator (|) takes the output (by default, STDOUT) of one command and directs it into the input (by default, STDIN) of another command. For example, the following command sorts a directory:
  107.  
  108. dir | sort
  109.  
  110. In this example, both commands start simultaneously, but then the sort command pauses until it receives the dir command's output. The sort command uses the dir command's output as its input, and then sends its output to handle 1 (that is, STDOUT).
  111.  
  112. Combining commands with redirection operators
  113. You can create custom commands by combining filter commands with other commands and file names. For example, you can use the following command to store the names of files that contain the string "LOG":
  114.  
  115. dir /b | find "LOG" > loglist.txt
  116.  
  117. The dir command's output is sent through the find filter command. File names that contain the string "LOG" are stored as a list of file names (for example, NetshConfig.log, Logdat.svd, and Mylog.bat) in the Loglist.txt file.
  118.  
  119. To use more than one filter in the same command, separate the filters with a pipe (|). For example, the following command searches every directory on drive C:, finds the file names that include the string "Log", and then displays them in one Command Prompt window at a time:
  120.  
  121. dir c:\ /s /b | find "LOG" | more
  122.  
  123. By using a pipe (|), you direct Cmd.exe to send the dir command output through the find filter command. The find command selects only file names that contain the string "LOG." The more command displays the file names that are selected by the find command, one Command Prompt window at a time. For more information about filter commands, see Using filters.
   

в начало страницы | новое
 
Поиск
Настройки
Твиттер сайта
Статистика
Рейтинг@Mail.ru