Version 3 of Automating sftp with Tcl

Updated 2007-06-25 18:18:43 by LV

George Peter Staplin: sftp (ssh FTP) has a wonderful feature that allows for executing a script. The script below automates the procedure of uploading files from a local public_html to a network.

To make it easier you can use ssh public keys, so that you don't have to type the password repeatedly. I suggest that you generate a public key (~/.ssh/id_dsa.pub), and upload it to the server's ~/.ssh/authorized_keys, so that you don't need a password.

The authentication agent can help make it easier to manage key passwords.

 $ crontab -l
 @reboot ssh-agent -s | grep -v echo > $HOME/.ssh-agent

Then I just type ssh-add after I have started my box, and enter the private key password.


 #!/usr/bin/env tclsh8.4

 proc main {argc argv} {
  if {$argc < 1} {
   puts stderr "syntax is: [info script] file"
   return 1
  }

  set dir [file normalize .]
  set remote_dir [string range $dir [string first public_html $dir] end]

  puts REMOTE:$remote_dir

  set fd [open _script_ w]

  # Prefix the mkdir with - to avoid termination if it already exists.
  puts $fd "-mkdir -p $remote_dir"
  puts $fd "cd $remote_dir"

  foreach f $argv {
   puts "PUT $f"
   puts $fd "put $f\nls -l $f"
  }

  puts $fd quit

  close $fd

  if {[catch {exec sftp -b _script_ [email protected]} r] && $::errorCode ne "NONE"} {
   puts stderr ERRORCODE:$::errorCode
   puts stderr ERROR:$r
   return 1
  }
  puts $r 

  file delete _script_

  return 0
 }
 exit [main $::argc $::argv]

Usage:

 $ pwd 
 /home/gps/archive/public_html/tmp
 $ pubup foo.jpg

At this point foo.jpg should be uploaded to the server's public_html/tmp.


Category Internet