How to transfer file between local and remote host using scp

In this article, we will learn how to transfer file using SCP . SCP stand for secure copy protocol. Its network protocol based on ssh (secure shell) that allow to transfer file/directory from remote  local,local to remote host and remote to remote host. 

 

Additionally, you can use scp command in batch file or shell script to automate the file transfer to full fill your daily, weekly, monthly and yearly task to eliminate the manual process. 

 

Steps to learn how to transfer file using SCP.

How to use SCP commands: –

#Copy file from remote host to local host.

scp username@remote_host:/remote/file.txt /local/file.txt

 

#Copy directory from remote host to local host.

scp username@remote_host:/remote/directory /local/directory

 

#Copy file from local host to remote host.

scp /local/file.txt username@remote_host:/remote/file.txt

 

#Copy directory from local host to remote host.

scp /local/directory username@remote_host:/remote/directory

 

#Copy file from remote host to remote host.

scp username1@remote_host1:/remote/file.txt username2@remote_host2:/remote/file.txt

 

#Copy directory from remote host to remote host.

scp username1@remote_host1:/remote/directory username2@remote_host2:/remote/directory

 

While doing the manual copy using scp, after press enter it will prompt for password.

how to transfer file
how to transfer file using SCP.

 

 

To automate the file transfer on Linux, Unix and Solaris server just prepare the shell script file(filetransfer.sh) as below given example. After that schedule it via cronjob.

Before going to schedule shell script ( filetransfer.sh), need to be generate a public and private key pair between both host for password less login (without prompting password).

 

Shell Script for how to transfer file from local to remote machine:-

#!/bin/ksh

cd /data01/scripts/csvfile

CURR_DT=`date  –date=”yesterday”  +%d-%m-%Y`

CSV_FILE1=leave_$CURR_DT.csv

Scriptfile=/data01/scripts/tadacsvfilefromftp.sh

export Scriptfile

 

scp [email protected].*.*:/home/employee/data/$CSV_FILE1 /data01/scripts/csvfile/$CSV_FILE1

cd /data01/scripts/csvfile

#Check CSV file exist on server.

if [[  -f $CSV_FILE1 ]]; then

echo “LEAVE File Rceiving Process was Successful  and ‘$CSV_FILE1’ exist”

else

echo “Leave File Receiving Process Failed ‘$CSV_FILE1’ Does not exist at `hostname`. Please contact System Administrator! $Scriptfile” | mailx -s “CSV File Receiving Failed from FTP Server” abc@**.com,support@***.com

fi

Hope we are able to how to transfer file using scp from local to remote and vice versa.

Related/References:-

Leave a Comment