Last active
April 14, 2021 14:45
-
-
Save kwent/e2c34c2dfd01a194a49a to your computer and use it in GitHub Desktop.
Create a ruby pseudo terminal (PTY) and invoke an interactive command (SFTP)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'pty' | |
require 'expect' | |
PTY.spawn('sftp [email protected]:/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