Advertisement
apcehypo

Ping&Eject

Feb 18th, 2014
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 2.33 KB | None | 0 0
  1. import std.stdio;
  2. import std.algorithm;
  3. import std.datetime;
  4. import std.path;
  5. import std.process;
  6. import core.thread;
  7. import std.conv;
  8.  
  9. string currentDateTime() {
  10.   return findSplit(Clock.currTime().toString, ".")[0];
  11. }
  12.  
  13. enum MAX_ATTEMPTS = 3;
  14. enum SLEEP_TIME = 10;
  15. enum MAX_WAIT_REBOOT_TIME = 300; //5 минут
  16.  
  17. int main(string[] argv) {
  18. //  argv ~= "192.168.1.43";
  19.   void ShowUsage() {
  20.     auto exeName = baseName(argv[0]);
  21.     writeln("Usage: "~exeName~" <IP-address or DNS-name>\n\rExample: "~exeName~" 192.168.1.23");
  22.   }
  23.   if (argv.length != 2) {
  24.     ShowUsage();
  25.     return 1;
  26.   }
  27.   auto ip = argv[1];
  28.   writeln("Ping: "~ip~" | Started: "~currentDateTime);
  29.  
  30.   auto attempts = MAX_ATTEMPTS;
  31.   auto attemptsMultiplier = 1;
  32.   auto sleepMultiplier = 1;
  33.   while (true) {
  34.     while (attempts > 0){
  35.       core.thread.Thread.sleep(dur!("seconds")(sleepMultiplier * SLEEP_TIME));
  36.       //посылаем 3 пинга, хотя бы один не прошёл - не доступен
  37.       if ((system("ping -n 1 -w 50 "~ip~" > nul") && system("ping -n 1 -w 50 "~ip~" > nul") && system("ping -n 1 -w 50 "~ip~" > nul")) == 0) {
  38.         writeln(currentDateTime~": ping succeed");
  39.         attempts = MAX_ATTEMPTS;
  40.         attemptsMultiplier = 1;
  41.         sleepMultiplier = 1;
  42.       }
  43.       else {
  44.         attempts -= sleepMultiplier;
  45.         if (attempts < (MAX_ATTEMPTS / attemptsMultiplier)) {
  46.           if (sleepMultiplier == 1) {
  47.             writeln(currentDateTime~": ping failed! Will try "~to!string(attempts)~" more times before eject CD.");
  48.           }
  49.           else {
  50.             writeln(currentDateTime~": timeout expired. Re-ejecting CD and wait for boot longer.");
  51.             attemptsMultiplier++;
  52.             break;
  53.           }
  54.         }
  55.         else {
  56.           writeln(currentDateTime~": waiting for boot. Will re-try in "~to!string(attempts * SLEEP_TIME)~" seconds.");
  57.           sleepMultiplier = 5;
  58.         }        
  59.       }
  60.     }
  61.     writeln("Ejecting CD-ROM...");
  62.     system(`powershell $cds = (New-Object -ComObject "WMPlayer.OCX").cdromCollection; for($i=0;$i -lt $cds.Count;$i++) { $cds.Item($i).Eject() }`);
  63.     attempts = attemptsMultiplier * (MAX_WAIT_REBOOT_TIME / SLEEP_TIME); //достаточное количество попыток для запуска компа
  64.   }
  65.   return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement