Skip to content

Instantly share code, notes, and snippets.

Last active April 14, 2021 14:45
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Create a ruby pseudo terminal (PTY) and invoke an interactive command (SFTP)
require 'pty'
require 'expect'
PTY.spawn('sftp') do |input, output|
# Say yes to SSH fingerprint
input.expect(/fingerprint/, 2) do |r|
output.puts "yes" if !r.nil?
# Enter SFTP password
input.expect(/password/, 2) do |r|
output.puts 'your_sftp_password' if !r.nil?
input.expect(/sftp/) do
# List folders and files in `/uploads`
output.puts 'ls'
# Check if folder named `foo` exist
input.expect(/foo/, 1) do |result|
is_folder_exist = result.nil? ? false : true
# Create `foo` folder if does'nt exist
output.puts "mkdir foo" if !is_folder_exist
# Change directory to `foo`
output.puts "cd foo"
# Upload `/path/to/local/foo.txt` in `foo` folder as `foo.txt`
output.puts "put /path/to/local/foo.txt foo.txt"
# Exit SFTP
output.puts "exit"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment