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

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.