22
Fri, Nov
1 New Articles

Automate Your File Transfers Using FTP on the IBM i

RPG
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Create a reusable program to make automating your file transfers easy.

 

File Transfer Protocol (FTP) is a popular way to get your files from one computer to another over the network. The IBM i makes it easy to do this, and I will show you how to create a reusable program that will make your automation of the process even easier.

Interactive FTP on the IBM i

Prior to automating your FTP process, you should test your file transfer interactively. For this example, we will be uploading an XML file named mcpress.xml onto a fictitious server:

 

Fictitious Target FTP Server Information

Target FTP Server

ftp.example.com

User Name

tomsnyder

Password

mcpress

           

Testing the FTP process interactively will ensure that the IBM i has access to the server and that the user name and password are active on the target server. You can do this by typing FTP or STRTCPFTP on the command line and prompting it to enter the DNS name or IP address of the server, or you can enter the FTP server information with either of these commands:

 

FTP RMTSYS('ftp.example.com')

 

or

 

STRTCPFTP RMTSYS('ftp.example.com')

 

Once you have successfully connected to the FTP server, you will enter your user name and password interactively. To complete the account verification, you should use the put command to upload a file to make sure you have the authority to do this.

 

For our example, we will be uploading an XML file from the IFS. I like to ensure that we are using namefmt 1 to indicate the file location in a directory format and specifying asc to perform an ASCII transfer. Here are the commands to execute at the FTP command line to accomplish the task:

 

namefmt 1

 

asc

 

put /Public/mcpress.xml

 

quit

 

Upon successful execution of these commands, you will have uploaded the XML file to your target FTP server. You can verify this by signing back onto the FTP server and executing the ls command to see your file on the server. Then type quit to close the connection.

 

Well, that was pretty useful information. But I am sure you do not want to manually send your files on a regular basis. So let's create a program to do it for us.

Using FTP in Batch

In order to automate the FTP process, we will most likely want to run it in batch. To do this, you can call the STRTCPFTP command, specifying the target FTP server location. When you do this, it will look for a file called INPUT in your library list to execute the FTP commands sequentially.

 

For our example, we will be creating a new physical file called FTPINPUT. I like to do this in case IBM provides this file during an upgrade; this way, that wouldn't doesn't cause problems with our existing file or delete all of the commands that are compiled as it is being built. To use the FTPINPUT file, we will just override the INPUT file to use our new FTPINPUT file.

 

The FTPINPUT file will be a physical file containing a single field that is large enough to accommodate most expected commands that you would be executing, with a little extra. I have chosen to set the field size to 2,000 characters, but you can set yours to be any size you feel sufficient. Here's the DDS for the FTPINPUT physical file:

 

A          R FTPFMT    

A            FTPCMD      2000     

 

Once you have the FTPINPUT file created with the MCPRESS member, you can enter the commands to be sequentially executed by STRTCPFTP. The first record in the file will contain the user name and password. So, using the FTP information from the table above, the first record of FTPINPUT will be this: 

 

tomsnyder mcpress

 

The rest of the records in FTPINPUT will be populated with the contents previously mentioned. A separate record will need to be created for each line.

Automated FTP on the IBM i

Putting in the extra effort at the beginning of implementing your automated FTP will save you a lot of time further down the line, as I have found out for myself. You could just create the FTPINPUT file, override it in a CL, and call the STRTCPFTP command from within a CL, and you'd be done. It sounds simple, and it sounds great, but what happens is that your automated FTP process begins to grow as you support more and more servers. Then you find yourself wanting to do more with your FTP process, which requires capabilities that you would need to use RPG for. At this point, you'd really wish that you had written the program in RPG, which is why we will be creating our program in RPG instead of CL.

 

To make our FTP program more flexible, we could put our server information into a physical file to be used with our STRTCPFTP command. Chances are that you may be supporting multiple sites for multiple purposes, so we could use these attributes as the composite key in our physical file to retrieve the location of the target FTP server. This would easily accommodate changes in the target FTP server that could support a change of FTP servers, failover, or different phases of development with a test and production server. Here's the DDS for the FTPSERVERS physical file:

 

A          R FTPSFMT 

A            FTPSITE       10     

A            FTPJOB        10        

A            FTPSVR       512     

A          K FTPSITE              

A          K FTPJOB     

 

As you start using this program more and more, you will find that you will be happy you set this up in the beginning.

 

We will be using FTPSERVERS as the name of our physical file, and here are the contents that we will be using for this example:

 

Contents of FTPSERVERS Physical File

Field

Value

FTPSITE

SCRANTON

FTPJOB

MCPRESS

FTPSVR

ftp.example.com

 

To keep this article within a reasonable size, we will only be using FTPSERVERS to store the location of the target server. Later on, you may want to consider putting the user name and password of the file in the FTPSERVERS file and building the FTPINPUT within the program. Or maybe you will want to encrypt the user name and password. You could store the user name and password as an encrypted value in the FTPSERVERS file, decrypt it in the program, create the FTPINPUT with the decrypted value, and clear the file when you are done--all future possibilities that can be easily implemented using RPG.

 

OK, we have all of the concepts and files to be used with our program defined. Now we can write the code! Here's the RPG program to perform the FTP upload of the XML file.

 

FFTPSERVERSIF   E           K DISK

 

D**********************************************************************

 

DARGS             DS

 

D ARGSITE                       10A

 

D ARGJOB                        10A

 

D* Prototype for QCMDEXC

 

D ExecuteCommand...

 

D                 PR                  extPgm('QCMDEXC')

 

D  argInCommand              65535A   const options(*varsize)

 

D  argInLength                  15P 5 const

 

D*

 

D CMD             S           1024A

 

D DSPBYTES        S             52A

 

D*

 

C/EJECT

 

C     *ENTRY        PLIST

 

C                   PARM                    ARGS

 

C     FTPKLIST      CHAIN     FTPSERVERS                         68

 

C                   IF        *IN68 = *OFF

 

C                   EVAL      CMD = 'OVRDBF FILE(INPUT)'

 

C                                 + ' TOFILE(FTPINPUT)'

 

C                                 + ' MBR(' + %TRIM(ARGJOB) + ')'

 

C                   CALLP     ExecuteCommand(%trim(CMD):%len(%trim(CMD)))

 

C*

 

C                   EVAL      CMD = 'STRTCPFTP'

 

C                                 + ' RMTSYS('''

 

C                                 + %trim(FTPSVR) + ''')'

 

C                   CALLP     ExecuteCommand(%trim(CMD):%len(%trim(CMD)))

 

C                   ELSE

 

C                   EVAL      DSPBYTES = 'INVALID PARMS!'

 

C                                      + ' SITE: ' + %TRIM(ARGSITE)

 

C                                      + ' JOB: ' + %TRIM(ARGJOB)

 

C     DSPBYTES      DSPLY

 

C                   ENDIF

 

C                   EVAL      *INLR = *ON

 

C*

 

C     FTPKLIST      KLIST

 

C                   KFLD                    ARGSITE

 

C                   KFLD                    ARGJOB

 

After you change the FTP server settings to the appropriate values for your FTP server, you can run the program with the key information for the FTPSERVER file:

 

CALL MYPGM 'SCRANTON  MCPRESS   ' 

 

A successful FTP transfer will result in something similar to this:

 

 

Enter an FTP subcommand.

   > namefmt 1

   500 'SITE NAMEFMT 1': command not understood

   Client NAMEFMT is 1.

   Enter an FTP subcommand.

   > asc

   200 Type set to A.

   Enter an FTP subcommand.

   > put /Public/mcpress.xml

   227 Entering Passive Mode (12,345,678,90,12,345).

   125 Data connection already open; Transfer starting.

   226 Transfer complete.

    10127 bytes transferred in 0.023 seconds. Transfer rate 432.085 KB/sec.

   Enter an FTP subcommand.

   > quit

   221

   Press ENTER to end terminal session.

    

Download the Code

You can download the code used in this article--as well as the fixed-format version--by clicking here.

 

Uploading Physical File Members

If you wanted to use FTP to send a physical file member to the target server, you could use NAMEFMT 0 or 1. If you were to upload a physical file member of MCPRESS from a file named MYFILE that resides in a library named MYLIB, you could use either of the following naming formats: 

 

NAMEFMT

Physical File Member

0 (Library File Naming Format)

MYLIB/MYFILE.MCPRESS

1 (Common FTP Naming Format)

/QSYS.LIB/MYLIB.LIB/MYFILE.FILE/MCPRESS.MBR

 

 

The following commands are two different ways to upload the same physical file member with different name formats:

 

Upload the file using NAMEFMT 0:

 

put MYLIB/MYFILE.MCPRESS

 

Upload the file using NAMEFMT 1:

 

put /QSYS.LIB/MYLIB.LIB/MYFILE.FILE/MCPRESS.MBR

 

More Information

 

For more information on FTP on the IBM i, you can go to the IBM Web site and read all about it.

 

 

Thomas Snyder

Thomas Snyder has a diverse spectrum of programming experience encompassing IBM technologies, open source, Apple, and Microsoft and using these technologies with applications on the server, on the web, or on mobile devices.

Tom has more than 20 years' experience as a software developer in various environments, primarily in RPG, Java, C#, and PHP. He holds certifications in Java from Sun and PHP from Zend. Prior to software development, Tom worked as a hardware engineer at Intel. He is a proud United States Naval Veteran Submariner who served aboard the USS Whale SSN638 submarine.

Tom is the bestselling author of Advanced, Integrated RPG, which covers the latest programming techniques for RPG ILE and Java to use open-source technologies. His latest book, co-written with Vedish Shah, is Extract, Transform, and Load with SQL Server Integration Services.

Originally from and currently residing in Scranton, Pennsylvania, Tom is currently involved in a mobile application startup company, JoltRabbit LLC.


MC Press books written by Thomas Snyder available now on the MC Press Bookstore.

Advanced, Integrated RPG Advanced, Integrated RPG
See how to take advantage of the latest technologies from within existing RPG applications.
List Price $79.95

Now On Sale

Extract, Transform, and Load with SQL Server Integration Services Extract, Transform, and Load with SQL Server Integration Services
Learn how to implement Microsoft’s SQL Server Integration Services for business applications.
List Price $79.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: