Skip to content

Instantly share code, notes, and snippets.

@jjam3774
Last active July 29, 2020 23:03
Show Gist options
  • Save jjam3774/c1c4997f9af1091b2730 to your computer and use it in GitHub Desktop.
Save jjam3774/c1c4997f9af1091b2730 to your computer and use it in GitHub Desktop.
Demonstration of PTY for Automating Interactive Applications
#!/usr/bin/ruby
require 'expect'
require 'pty'
# PTY without expect can easily automate interactive programs...
PTY.spawn('./inter.rb'){|o,i,p|
i.puts("yes")
o.gets #not needed to work just included it to clean up look on-screen
i.puts("yes")
o.gets
i.puts("yes")
o.gets
begin
o.each_line{|k|
puts k
}
rescue Errno::EIO
ensure
Process.wait p
end
}
# PTY without expect can easily automate interactive programs...
PTY.spawn('fdisk /dev/sda'){|o,i,p|
i.puts('p')
o.gets
i.puts('m')
o.gets
i.puts('l')
o.gets
i.puts('q')
o.gets
begin
o.each_line{|k|
puts k
}
rescue Errno::EIO
ensure
Process.wait p
end
}
# There may be times to bring in Expect. Some programs will note respond
# unless you have expect involved... sync is included to ensure that we
# get output in real-time.
PTY.spawn('ssh localhost'){|o,i,p|
#o.sync = true
#i.sync = true
$expect_verbose = true # shows actions on screen
if o.expect(/yes\/no/, 1)
i.puts('yes')
o.expect(/[Pp]assword/)
i.puts('sister')
o.expect(/[#$]/)
i.puts('dmidecode -t bios')
i.puts('exit')
else
o.expect(/[Pp]assword/, 1)
i.puts('sister')
o.expect(/[#$]/)
i.puts('dmidecode -t bios')
i.puts('exit')
end
begin
o.each_line{|k|
puts k
}
rescue Errno::EIO
ensure
Process.wait p
end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment