Create a gist now

Instantly share code, notes, and snippets.

@kwent /sftp.rb
Last active Mar 1, 2017

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