TweetFollow Us on Twitter

More Scriptable Access to Remote Directories

Volume Number: 22 (2006)
Issue Number: 7
Column Tag: AppleScript Essentials

More Scriptable Access to Remote Directories

by Benjamin S. Waldie

For some time now, we have been discussing various ways to interact with directories on remote servers using scriptable FTP clients. So far, we have discussed scripting Fetch (http://www.fetchsoftworks.com) and Transmit (http://www.panic.com), both of which are widely used scriptable FTP clients for the Macintosh. However, these applications are not the only options available to you. In this month's column, we will discuss some other options for interacting with remote directories, including using Cyberduck, URL Access Scripting, and more.Please note that in order to test the code throughout this column, you will need to acquire access to an FTP server, either remote or on your local network. If you have been following along, the past few months, then you may recall that for testing, I created a local FTP server by enabling FTP access on another machine within my office.

Cyberduck

The first option for remote directory interaction that we will discuss is an application called Cyberduck (see figure 1). Cyberduck is an open source scriptable FTP/SFTP client, which you can find on the web at <http://cyberduck.ch/>.



Figure 1. Cyberduck

Using Cyberduck, you can connect to remote servers, browse their directory structures, upload files, download files, and more.

Connecting to a Server

In order to begin interacting with a remote directory using Cyberduck, you will need to open a connection to the server that houses that directory. This is done by creating a browser window in Cyberduck, if one does not already exist, and then telling that browser window to connect to the server. The following example code demonstrates how this may be done:

set theServerAddress to "10.0.1.3"
set theUserName to "myUserName"
set thePassword to "myPassword"
tell application "Cyberduck"
   set theBrowser to make new browser
   tell theBrowser
      connect to theServerAddress as user theUserName with password thePassword
   end tell
end tell

In the code above, the result of the make command is a reference to the newly created browser document. This variable is then used to target the browser in order to make a new connection using the connect command. In Cyberduck, browser windows may also be referred to by their index, or front to back positioning. For example, the following code would target the frontmost browser window.

tell application "Cyberduck"
   tell browser 1
      -- do something
   end tell
end tell

Changing Folders

Once a Cyberduck browser window is connected to a server, you may wish to navigate to another directory on the server. This may be done by using the change folder command. The following code will attempt to navigate to the Documents > FTP Main directory in the front browser window.

tell application "Cyberduck"
   tell browser 1
      change folder to "Documents/FTP Main/"
   end tell
end tell

Uploading Files

To upload files using Cyberduck, you may use the upload command, and specify a file reference that you would like to upload. You may also wish to make use of the refresh command to update Cyberduck's display once the upload is complete.

The following example code will prompt the user to select a file. It will then upload the file to the current directory in the front browser window.

set theFile to choose file with prompt "Please select a file to upload:" without invisibles
tell application "Cyberduck"
   tell browser 1
      upload file theFile
      refresh
   end tell
end tell

In the example code above, you may be questioning the use of the word file, following the upload command, since my variable theFile already contains an AppleScript alias reference. In this case, the word file is actually a labeled parameter for Cyberduck's upload command. The upload command will accept an AppleScript alias or a POSIX-style path as a value for its file parameter. For example, the following example code would function in the same manner as the previous example:

set theFile to POSIX path of (choose file with prompt "Please select a file to upload:" without invisibles)

tell application "Cyberduck"
   tell browser 1
      upload file theFile
      refresh
   end tell
end tell

Figure 2 shows a directory in Cyberduck, where a file has been uploaded using the code from our previous examples.



Figure 2. A Directory in Cyberduck

Listing Folder Contents

To retrieve a directory listing on a connected server, you may make use of the browse command. When using this command, specify the path to the folder whose directory listing you wish to retrieve as the value for the command's folder parameter. In the example code below, I have chosen to list the directory contents of the current folder. I am doing this by referencing the working folder property of the front browser window, and specifying that value in the browse command's folder parameter.

tell application "Cyberduck"
   tell browser 1
      browse folder working folder
   end tell
end tell
--> {"JobImage1.png"}

In this case, my current folder contained only a single file, as indicated in the list that is returned as a result of the browse command.

Downloading Files

To download remote files using Cyberduck, make use of the download command. Specify the path to the item you wish to download as a value for the download command's file parameter, and the desired output folder path as a value for the download command's to parameter.

tell application "Cyberduck"
   tell browser 1
      download file "JobImage1.png" to path to desktop folder
   end tell
end tell

When using the download command, you may optionally choose to specify a value for the command's as parameter, in order to specify a custom name to use when saving the downloaded file.

Disconnecting

To disconnect a browser window in Cyberduck, use the disconnect command. After doing so, if you will not be making another connection immediately, you may also want to use the close command to close the browser window. The following example code will disconnect and close the frontmost browser window.

tell application "Cyberduck"
   tell browser 1
      disconnect
      close
   end tell
end tell

Mounting a Remote Server on the Desktop

So far, we have focused on using scriptable FTP/SFTP client applications as the means for connecting to servers and interacting with their remote directories. However, Mac OS X also supports the ability to connect to a server using the Finder. Once connected to a server, the Finder may be used to navigate the directory structure on that server, upload and download files, and perform other tasks in the same manner that you would with a local directory.

To connect to a server in the Finder, you can make use of the mount volume command. This command can be found in the File Commands suite in the StandardAdditions scripting addition, which is installed with Mac OS X, and is located in the System > Library > ScriptingAdditions folder on your machine.

The mount volume command accepts a direct parameter of the volume, or a server URL, to which you want to connect. It also accepts labeled parameters, allowing you to specify the name or IP address of the server, the username, and password. The following example code demonstrates the basic usage of this command, and will mount a shared volume on my local network.

set theServerAddress to "10.0.1.3"
set theUserName to "myUserName"
set thePassword to "myPassword"
set theVolume to "bwaldie"
mount volume theVolume on server theServerAddress as user name theUserName with password thePassword
--> file "bwaldie:"

As mentioned briefly above, you can also use the mount volume command to connect to a server volume by specifying a server URL, rather than specifying separate parameters. To access a shared volume, you will typically begin the URL with afp://, or the Apple filing protocol. The mount volume command will also accept an smb:// file protocol for accessing SMB servers.

When specifying a server URL, you can choose to make use of the as user name and with password parameters. For example:

mount volume "afp://" & theServerAddress & "/" & theVolume as user name theUserName 
with password thePassword
--> file "bwaldie:"

Alternatively, you may choose to include the username and password within the server URL itself. The following code shows the proper method for doing this.

mount volume "afp://" & theUserName & ":" & thePassword & "@" & theServerAddress 
& "/" & theVolume
--> file "bwaldie:"

The mount volume command may also be used to connect to a server via FTP. The method for doing so is similar to the process of connecting to a server volume via the Apple file sharing protocol. The difference is that the server's URL should begin with an ftp:// protocol. For example:

set theServerAddress to "10.0.1.3"
set theUserName to "myUserName"
set thePassword to "myPassword"
mount volume "ftp://" & theUserName & ":" & thePassword & "@" & theServerAddress
--> file "bwaldie@10.0.1.3:"

Once connected to a server after using the mount volume command, the volume should appear on your desktop, and may be navigated in the Finder either manually or via AppleScript. See Figure 3.



Figure 3. A Mounted Server Volume

URL Access Scripting

Another method of working with remote directories is with the use of URL Access Scripting, which is installed with Mac OS X. URL Access Scripting can be found in the System > Library > ScriptingAdditions folder. Although this location may give the impression that URL Access Scripting is a scripting addition, it is, in fact, a background application, and must be targeted using a tell statement, just like any other application.

As you will find, URL Access Scripting does not provide the full range of access to remote directories that we have seen with other applications like Fetch, Transmit, Cyberduck, and the Finder. However, it does provide a fairly quick way to upload and download files using AppleScript.

Uploading Files

To upload a file using URL Access Scripting, make use of the upload command. When using this command, specify a reference to the file you want to upload as the direct parameter. You must also specify a URL for the remote destination folder as a value for the command's to labeled parameter. To upload to a protected remote directory, you may choose to include the username and password directly within the destination URL, in the same way that we discussed when mounting server volumes using the mount volume command.

The following example code will prompt the user to select a file to be uploaded. It will then upload the selected file to a remote directory using URL Access Scripting.

set theServerAddress to "10.0.1.3"
set theUserName to "myUserName"
set thePassword to "myPassword"
set theDirectory to "Documents/FTP Main/"
set theFile to choose file with prompt "Please select a file to upload:" without invisibles
set theURL to "ftp://" & theUserName & ":" & thePassword & "@" & theServerAddress & "/" & theDirectory
tell application "URL Access Scripting"
   upload theFile to theURL
end tell
--> true

URL Access Scripting's upload command also possesses a number of optional parameters, which may be utilized, if desired. For example, a value may be specified for the replacing parameter to indicate whether an existing duplicate item should be replaced on the remote directory when performing the upload. A binhexing parameter may be used to automatically binhex the item being uploaded.

tell application "URL Access Scripting"
   upload theFile to theURL replacing yes without binhexing
end tell
--> true

If you prefer not to include a username and password in the destination URL itself, you may optionally choose to make use of the authentication parameter for the upload command. For example:

set theURL to "ftp://" & theServerAddress & "/" & theDirectory
tell application "URL Access Scripting"
   upload theFile to theURL with authentication
end tell
--> true

Making use of the authentication parameter will cause an authentication dialog to be displayed when the command is executed, allowing the user to manually provide a username and password. See figure 4.



Figure 4. URL Access Scripting Authentication Dialog

Downloading Files

To download a file using URL Access Scripting, use the download command, and specify the URL of the remote file you want to download, as well as the file specification for the destination file. Like uploading files, if the target file resides on a protected server, you may choose to include the username and password within the target URL itself, or you may make use of the upload command's authentication parameter, allowing the user to provide this information during execution. The following example code will attempt to download a file to my desktop, displaying an authentication dialog when run.

set theFileURL to "ftp://10.0.1.3/Documents/FTP Main/JobImage1.png"
set theDestinationFile to (path to desktop folder as string) & "JobImage1.png"
tell application "URL Access Scripting"
   download theFileURL to file theDestinationFile with authentication
end tell
--> file "Macintosh HD:Users:bwaldie:Desktop:JobImage1.png"

In addition to downloading files from FTP servers, URL Access Scripting's download command may also be used to download standard web pages. For example, the following code will download Apple's main web page to a file named index.html on the desktop.

set theFileURL to "http://www.apple.com"
set theDestinationFile to (path to desktop folder as string) & "index.html"
tell application "URL Access Scripting"
   download theFileURL to file theDestinationFile
end tell
--> file "Macintosh HD:Users:bwaldie:Desktop:index.html"

curl

So far, all of the methods we have discussed for interacting with remote servers have involved AppleScriptable applications. However, in Mac OS X, with the power of UNIX, there are other options available to you. There are numerous command line tools that may be used to interact with remote servers, which may be accessed from AppleScript by using the do shell script command. One such utility is curl, which is often utilized by AppleScript developers for uploading and downloading files.

Let me preface this section by saying that using curl for interacting with remote directories is not by any means covered in its entirety below. The capabilities of curl go far beyond what I will be touching on in this month's column. Furthermore, I am an AppleScript developer, and not a UNIX expert. Therefore, my knowledge of curl is a bit limited at present, as I have not had many opportunities to utilize it myself. Because of this, I am sure that the methods I will discuss below could be greatly enhanced and improved upon in order to provide greater reliability and functionality.

For more information on curl, I would recommend checking out its man page in the Terminal and/or browsing <http://curl.haxx.se/>.

Uploading Files

To upload a file using curl, specify a destination file URL, followed by the -T option and the path to the file to be uploaded. As in some of the previous examples we have seen, a username and password may be included directly within the destination file URL.

This code will use curl to upload a PNG image on my desktop to a directory on a protected FTP server.

set theFileURL to quoted form of "/Users/bwaldie/Desktop/JobImage1.png"
set theOutputFile to quoted form of 
   "ftp://myUserName:myPassword@10.0.1.3/Documents/FTPMain/JobImage1.png"
set theCommand to "curl " & theOutputFile & " -T " & theFileURL
do shell script theCommand

Downloading Files

To download a file using curl, specify the target file's URL, followed by the -o option and the local path to the output file.

The following example code demonstrates how to download a remote file on a protected FTP server using curl. This particular file will be downloaded to my desktop.

set theFileURL to quoted form of 
   "ftp://myUserName:myPassword@10.0.1.3/Documents/FTP Main/JobImage1.png"
set theOutputFile to quoted form of "/Users/bwaldie/Desktop/JobImage1.png"
set theCommand to "curl " & theFileURL & " -o " & theOutputFile
do shell script theCommand

In Closing

By now, you should have a variety of options for interacting with remote directories using AppleScript, and even some example code to help you to get started. As always, when working with a scriptable application, you may want to find out if the developer of that application provides example AppleScripts as well. Cyberduck, for example, comes with a number of example AppleScripts, which are all unlocked and available to you for editing. Be sure to check them out.

Until next time, keep scripting!

    Interested in learning more about a specific AppleScript-related topic? Feel free to send your topic suggestions or requests to me at ben@automatedoworkflows.com for consideration, and possible inclusion in future columns.


Ben Waldie is the author of the best selling books "AppleScripting the Finder" and the "Mac OS X Technology Guide to Automator", available from http://www.spiderworks.com. Ben is also president of Automated Workflows, LLC, a company specializing in AppleScript and workflow automation consulting. For years, Ben has developed professional AppleScript-based solutions for businesses including Adobe, Apple, NASA, PC World, and TV Guide. For more information about Ben, please visit http://www.automatedworkflows.com, or email Ben at ben@automatedworkflows.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Ride into the zombie apocalypse in style...
Back in the good old days of Flash games, there were a few staples; Happy Wheels, Stick RPG, and of course the apocalyptic driver Earn to Die. Fans of the running over zombies simulator can rejoice, as the sequel to the legendary game, Earn to Die... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Netflix Games expands its catalogue with...
It is a good time to be a Netflix subscriber this month. I presume there's a good show or two, but we are, of course, talking about their gaming service that seems to be picking up steam lately. May is adding five new titles, and there are some... | Read more »
Pokemon Go takes a step closer to real P...
When Pokemon Go was first announced, one of the best concepts of the whole thing was having your favourite Pokemon follow you in the real world and be able to interact with them. To be frank, the AR Snapshot tool could have done a lot more to help... | Read more »
Seven Knights Idle Adventure drafts in a...
Seven Knights Idle Adventure is opening up more stages, passing the 15k mark, and players may find themselves in need of more help to clear these higher stages. Well, the cavalry has arrived with the introduction of the Legendary Hero Iris, as... | Read more »
AFK Arena celebrates five years of 100 m...
Lilith Games is quite the behemoth when it comes to mobile games, with Rise of Kingdom and Dislyte firmly planting them as a bit name. Also up there is AFK Arena, which is celebrating a double whammy of its 5th anniversary, as well as blazing past... | Read more »
Fallout Shelter pulls in ten times its u...
When the Fallout TV series was announced I, like I assume many others, assumed it was going to be an utter pile of garbage. Well, as we now know that couldn't be further from the truth. It was a smash hit, and this success has of course given the... | Read more »
Recruit two powerful-sounding students t...
I am a fan of anime, and I hear about a lot that comes through, but one that escaped my attention until now is A Certain Scientific Railgun T, and that name is very enticing. If it's new to you too, then players of Blue Archive can get a hands-on... | Read more »
Top Hat Studios unveils a new gameplay t...
There are a lot of big games coming that you might be excited about, but one of those I am most interested in is Athenian Rhapsody because it looks delightfully silly. The developers behind this project, the rather fancy-sounding Top Hat Studios,... | Read more »
Bound through time on the hunt for sneak...
Have you ever sat down and wondered what would happen if Dr Who and Sherlock Holmes went on an adventure? Well, besides probably being the best mash-up of English fiction, you'd get the Hidden Through Time series, and now Rogueside has announced... | Read more »

Price Scanner via MacPrices.net

Apple Studio Display with Standard Glass on s...
Best Buy has the standard-glass Apple Studio Display on sale for $300 off MSRP for a limited time. Their price is the lowest available for a Studio Display among Apple’s retailers. Shipping is free... Read more
AirPods Max headphones back on sale for $449,...
Amazon has Apple AirPods Max headphones in stock and on sale for $100 off MSRP, only $449. The sale price is valid for all colors at the time of this post. Shipping is free: – AirPods Max: $449.99 $... Read more
Deal Alert! 13-inch M2 MacBook Airs on record...
Amazon has 13″ MacBook Airs with M2 CPUs in stock and on sale this week for only $829 in Space Gray, Silver, Starlight, and Midnight colors. Their price is $170 off Apple’s MSRP, and it’s the lowest... Read more
Apple Watch Ultra 2 on sale for $50 off MSRP
Best Buy is offering Apple Watch Ultra 2 models for $50 off MSRP on their online store this week. Sale prices available for online orders only, in-store prices may vary. Order online, and choose free... Read more
Apple introduces the new M4-powered 11-inch a...
Today, Apple revealed the new 2024 M4 iPad Pro series, boasting a surprisingly thin and light design that pushes the boundaries of portability and performance. Offered in silver and space black... Read more
Apple introduces the new 2024 11-inch and 13-...
Apple has unveiled the revamped 11-inch and brand-new 13-inch iPad Air models, upgraded with the M2 chip. Marking the first time it’s offered in two sizes, the 11-inch iPad Air retains its super-... Read more
Apple discontinues 9th-gen iPad, drops prices...
With today’s introduction of the new 2024 iPad Airs and iPad Pros, Apple has (finally) discontinued the older 9th-generation iPad with a home button. In response, they also dropped prices on 10th-... Read more
Apple AirPods on sale for record-low prices t...
Best Buy has Apple AirPods on sale for record-low prices today starting at only $79. Buy online and choose free shipping or free local store pickup (if available). Sale price for online orders only,... Read more
13-inch M3 MacBook Airs on sale for $100 off...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices, along with Amazon’s, are the lowest currently available for new 13″... Read more
Amazon is offering a $100 discount on every 1...
Amazon has every configuration and color of Apple’s 13″ M3 MacBook Air on sale for $100 off MSRP, now starting at $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD): $999 $100 off... Read more

Jobs Board

*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Relationship Banker *Apple* Valley Main - W...
…Alcohol Policy to learn more. **Company:** WELLS FARGO BANK **Req Number:** R-367184 **Updated:** Wed May 08 00:00:00 UTC 2024 **Location:** APPLE VALLEY,California Read more
Rehabilitation Technician - *Apple* Hill (O...
Rehabilitation Technician - Apple Hill (Outpatient Clinic) - PRN Location: York Hospital, York, PA Schedule: PRN/Per Diem Sign-On Bonus Eligible Remote/Hybrid Read more
LPN-Physician Office Nurse - Orthopedics- *Ap...
LPN-Physician Office Nurse - Orthopedics- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Medical Assistant Lead - Orthopedics *Apple*...
Medical Assistant Lead - Orthopedics Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.