CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/lib/expect.rb
Views: 1903
1
# Sourced from Ruby's ext/pty/lib/expect.rb to allow for access from Windows,
2
# which does not seem to have an issue using this particular method with
3
# sockets (pipes and other handles won't work, so don't use it for that).
4
# frozen_string_literal: true
5
$expect_verbose = false
6
7
# Expect library adds the IO instance method #expect, which does similar act to
8
# tcl's expect extension.
9
#
10
# In order to use this method, you must require expect:
11
#
12
# require 'expect'
13
#
14
# Please see #expect for usage.
15
class IO
16
# call-seq:
17
# IO#expect(pattern,timeout=9999999) -> Array
18
# IO#expect(pattern,timeout=9999999) { |result| ... } -> nil
19
#
20
# Reads from the IO until the given +pattern+ matches or the +timeout+ is over.
21
#
22
# It returns an array with the read buffer, followed by the matches.
23
# If a block is given, the result is yielded to the block and returns nil.
24
#
25
# When called without a block, it waits until the input that matches the
26
# given +pattern+ is obtained from the IO or the time specified as the
27
# timeout passes. An array is returned when the pattern is obtained from the
28
# IO. The first element of the array is the entire string obtained from the
29
# IO until the pattern matches, followed by elements indicating which the
30
# pattern which matched to the anchor in the regular expression.
31
#
32
# The optional timeout parameter defines, in seconds, the total time to wait
33
# for the pattern. If the timeout expires or eof is found, nil is returned
34
# or yielded. However, the buffer in a timeout session is kept for the next
35
# expect call. The default timeout is 9999999 seconds.
36
def expect(pat,timeout=9999999)
37
buf = ''.dup
38
case pat
39
when String
40
e_pat = Regexp.new(Regexp.quote(pat))
41
when Regexp
42
e_pat = pat
43
else
44
raise TypeError, "unsupported pattern class: #{pat.class}"
45
end
46
@unusedBuf ||= ''
47
while true
48
if not @unusedBuf.empty?
49
c = @unusedBuf.slice!(0)
50
elsif !IO.select([self],nil,nil,timeout) or eof? then
51
result = nil
52
@unusedBuf = buf
53
break
54
else
55
c = getc
56
end
57
buf << c
58
if $expect_verbose
59
STDOUT.print c
60
STDOUT.flush
61
end
62
if mat=e_pat.match(buf) then
63
result = [buf,*mat.captures]
64
break
65
end
66
end
67
if block_given? then
68
yield result
69
else
70
return result
71
end
72
nil
73
end
74
end
75
76