Advertisement
galleyworm

expect.ps1

Sep 2nd, 2013
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. $Source = @"
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Threading;
  6. using System.IO;
  7.  
  8. namespace Zh
  9. {
  10.     public class ZhExpect
  11.     {
  12.    
  13.         private Process ps;
  14.         private bool inProgress;
  15.         private Thread readPsOut;
  16.         private Thread readPsErr;
  17.         private volatile string receivedText = "";
  18.         private string log = "";
  19.         private object locker = new object();
  20.        
  21.         public ZhExpect() {
  22.             ps = new Process();
  23.             ps.StartInfo.UseShellExecute = false;
  24.             ps.StartInfo.RedirectStandardError = true;
  25.             ps.StartInfo.RedirectStandardInput = true;
  26.             ps.StartInfo.RedirectStandardOutput = true;
  27.         }
  28.    
  29.         public void spawn(String fileName, String arguments) {
  30.            
  31.             ps.StartInfo.Arguments = arguments;
  32.             ps.StartInfo.FileName = fileName;
  33.            
  34.             ps.Start();
  35.            
  36.             readPsOut = new Thread(ReadProcess);
  37.             readPsErr = new Thread(ReadProcess);
  38.            
  39.             inProgress = true;
  40.            
  41.             readPsOut.Start(ps.StandardOutput.BaseStream);
  42.             readPsErr.Start(ps.StandardError.BaseStream);
  43.            
  44.         }
  45.        
  46.         private void ReadProcess (object bs) {
  47.            
  48.             Stream bstream = (Stream) bs;
  49.             byte[] buffer = new byte[1000];
  50.             int count;
  51.             System.IAsyncResult readResult = bstream.BeginRead(buffer, 0, buffer.Length, null, null);
  52.            
  53.             while (inProgress) {
  54.                 if (readResult.IsCompleted) {
  55.                     count = bstream.EndRead(readResult);
  56.                     string currentReceivedText = System.Text.Encoding.UTF8.GetString(buffer, 0, count);
  57.                     lock (locker) {
  58.                         receivedText = receivedText + currentReceivedText;
  59.                         log = log + currentReceivedText;
  60.                     }
  61.                     Console.Write(currentReceivedText);
  62.                     readResult = bstream.BeginRead(buffer, 0, buffer.Length, null, null);
  63.                 }
  64.                 Thread.Sleep(10);
  65.             }
  66.         }
  67.  
  68.         public void Interact(string stopString) {
  69.            
  70.             StreamWriter psStreamWriter = ps.StandardInput;
  71.             System.ConsoleKeyInfo key;
  72.             String str = "";
  73.            
  74.             while(!ps.HasExited) {
  75.                
  76.                 key = Console.ReadKey(true);
  77.                
  78.                 if (key.Key.Equals(System.ConsoleKey.UpArrow)) psStreamWriter.Write("\x1b[A");
  79.                 else if (key.Key.Equals(System.ConsoleKey.DownArrow)) psStreamWriter.Write("\x1b[B");
  80.                 else if (key.Key.Equals(System.ConsoleKey.LeftArrow)) psStreamWriter.Write("\x1b[D");
  81.                 else if (key.Key.Equals(System.ConsoleKey.RightArrow)) psStreamWriter.Write("\x1b[C");
  82.                 else  {
  83.                     str = str + key.KeyChar;
  84.                     psStreamWriter.Write(key.KeyChar);
  85.                 }
  86.                
  87.                 if (str.Contains(stopString)) {
  88.                     for (int i = 0; i < stopString.Length-1; i++) {
  89.                         psStreamWriter.Write("\b");
  90.                     }
  91.                     break;
  92.                 }
  93.             }
  94.         }
  95.        
  96.         public bool Expect(string ExpectingString, int timeOut, bool cleanBuffer) {
  97.             System.DateTime startTime = System.DateTime.Now;   
  98.             do {
  99.                 lock(locker) {
  100.                     if (receivedText.Contains(ExpectingString)) {
  101.                         if (cleanBuffer) receivedText = "";
  102.                         return true;
  103.                     }
  104.                 }
  105.                 Thread.Sleep(10);
  106.             } while ((System.DateTime.Now - startTime).Seconds < timeOut);
  107.             return false;
  108.         }
  109.        
  110.         public void Send(string sendString) {
  111.             ps.StandardInput.Write(sendString);
  112.         }
  113.        
  114.         public string getLog(bool clear) {
  115.            string returnLog = log;
  116.            if (clear) {
  117.                log = "";
  118.            }
  119.             return returnLog;
  120.         }
  121.        
  122.         public void Close() {
  123.             inProgress = false;
  124.             readPsErr.Join();
  125.             readPsOut.Join();
  126.             ps.StandardInput.Write("\x03");
  127.             ps.StandardOutput.Close();
  128.             ps.StandardInput.Close();
  129.             ps.StandardError.Close();
  130.             if (!ps.HasExited) {
  131.                 ps.Kill();
  132.             }
  133.            
  134.         }
  135.     }
  136. }
  137. "@
  138. Add-Type -Language CSharp -TypeDefinition $Source
  139.  
  140. [Zh.ZhExpect] $plink
  141. [int32]       $expectTimeout = 5
  142.  
  143. function Spawn-Plink { 
  144.     param (
  145.         [parameter(Mandatory=$true)]
  146.         [alias("h")]
  147.         [string]$remoteHost,
  148.        
  149.         [alias("p")]
  150.         [string]$port = "",
  151.        
  152.         [alias("pr")]
  153.         [string]$proto = "ssh",
  154.        
  155.         [alias("l")]
  156.         [string]$login = "",
  157.        
  158.         [alias("pw")]
  159.         [string]$password = ""
  160.     )
  161.    
  162.     $script:plink = New-Object Zh.ZhExpect
  163.    
  164.     $argumentList = "-$proto"
  165.    
  166.     if ($port.length -gt 0) {
  167.         $argumentList = $argumentList + " -P $port"
  168.     }
  169.    
  170.     if ($proto -eq "ssh") {
  171.         if ($login.length -gt 0)    { $argumentList = $argumentList + " -l $login" }
  172.         if ($password.length -gt 0) { $argumentList = $argumentList + " -pw $password" }
  173.     }
  174.    
  175.     $argumentList = $argumentList + " " + $remoteHost
  176.  
  177.     $script:plink.Spawn("plink", $argumentList)
  178. }
  179.  
  180. function Expect {  
  181.     param(
  182.         [parameter(Mandatory=$true, Position=1)]
  183.         [alias("e")]
  184.         [String] $expectString,
  185.        
  186.         [parameter(Position=2)]
  187.         [alias("a")]
  188.         [Scriptblock] $action,
  189.        
  190.         [alias("t")]
  191.         [Int32] $timeOut = $script:expectTimeout
  192.     )
  193.    
  194.     if ($script:plink.Expect($expectString, $timeOut, $true)) {
  195.         $action.Invoke()
  196.     }
  197. }
  198.  
  199. function ext_Expect {  
  200.  
  201.     [String[]]$expStrings = @()
  202.     [ScriptBlock[]]$actions = @()
  203.    
  204.     for ($x=0; $x -le $Args.Length-1; $x=$x+2) {
  205.         if ($Args[$x].GetType().Name -eq "String") {
  206.             if ($Args[$x+1].GetType().Name -eq "ScriptBlock") {
  207.                 $expStrings += $Args[$x]
  208.                 $actions += $Args[$x+1]
  209.             } else { Write-Error -ErrorAction Stop ( "arg `"" + $Args[$x+1] +
  210.                                                      "`" has type a " + $Args[$x+1].GetType().Name +
  211.                                                      "; must be is not a ScriptBlock!") }
  212.         } else { Write-Error -ErrorAction Stop ("arg `"" + $Args[$x] +
  213.                                                 "`" has type a " + $Args[$x].GetType().Name +
  214.                                                 "; must be a String!") }
  215.     }
  216.    
  217.     for ($x=0; $x -le $actions.Length-1; $x++) {
  218.         $tmout = $script:expectTimeout
  219.         if ($script:plink.Expect($expStrings[$x], $script:expectTimeout, ($x == $actions.Length-1))) {
  220.             $actions[$x].Invoke()
  221.         }
  222.         $tmout = 0
  223.     }
  224. }
  225.  
  226. function Send {
  227.     param([parameter(Mandatory=$true)]
  228.           [string]$sendString
  229.     )
  230.     $script:plink.Send($sendString)
  231. }
  232.  
  233. function Interact {
  234.     param([parameter(Mandatory=$true)]
  235.           [string]$stopString
  236.     )
  237.     $script:plink.Interact($stopString)
  238. }
  239.  
  240. function Close-Plink {
  241.     $script:plink.Close()
  242. }
  243.  
  244. function Get-Log {
  245.     param(
  246.         [alias("c")]
  247.         [switch]$clear = $false
  248.     )
  249.     if ($clear) {
  250.         return $script:plink.getLog($true)
  251.     } else {
  252.         return $script:plink.getLog($false)
  253.     }
  254. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement