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

The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »

Price Scanner via MacPrices.net

Sunday Sale: Apple Studio Display with Standa...
Amazon has the standard-glass Apple Studio Display on sale for $300 off MSRP for a limited time. Shipping is free: – Studio Display (Standard glass): $1299.97 $300 off MSRP For the latest prices and... Read more
Apple is offering significant discounts on 16...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... Read more
Apple HomePods on sale for $30-$50 off MSRP t...
Best Buy is offering a $30-$50 discount on Apple HomePods this weekend on their online store. The HomePod mini is on sale for $69.99, $30 off MSRP, while Best Buy has the full-size HomePod on sale... Read more
Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more

Jobs Board

Licensed Practical Nurse - Womens Imaging *A...
Licensed Practical Nurse - Womens Imaging Apple Hill - PRN Location: York Hospital, York, PA Schedule: PRN/Per Diem Sign-On Bonus Eligible Remote/Hybrid Regular Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Operating Room Assistant - *Apple* Hill Sur...
Operating Room Assistant - Apple Hill Surgical Center - Day Location: WellSpan Health, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular 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
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.