Skip to content

Instantly share code, notes, and snippets.

@kwent
Last active April 14, 2021 14:45
Show Gist options
  • Save kwent/e2c34c2dfd01a194a49a to your computer and use it in GitHub Desktop.
Save kwent/e2c34c2dfd01a194a49a to your computer and use it in GitHub Desktop.
Create a ruby pseudo terminal (PTY) and invoke an interactive command (SFTP)
require 'pty'
require 'expect'
PTY.spawn('sftp username@sftp.domain.com:/uploads') 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"
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment