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

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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.