AzizShaw
AzizShaw

Reputation: 131

shell script to moving files from one server to another server using sftp

Here I am moving jars from server A to server B using sftp:

[mars@server33 ND_Jars]$ ls
   abc-5.5.0.jar     
   abc1-5.4.3.jar    
   abc2-5.5.0.jar   
   abc3-5.5.0.jar   
   abc4-com-5.5.0.jar

[mars@server33 ND_Jars]$ ll    
total 3552    
-rw-rw-r-- 1 mars mars 1184548 Jan  7 14:32 abc1-com-5.5.0.jar     
-rw-rw-r-- 1 mars mars 1130509 Dec 26 11:30 abc2-5.4.3.jar    
-rw-rw-r-- 1 mars mars   24694 Dec 30 17:27 abc3-5.5.0.jar    
-rw-rw-r-- 1 mars mars   45454 Dec 18 16:25 abc4-5.5.0.jar    
-rw-rw-r-- 1 mars mars 1236350 Jan  7 14:32 abc-5.5.0.jar    
[mars@server33 ND_Jars]$ sftp sftpuser@5     
Connecting to 10.0.14.19...     
[email protected]'s password:    
sftp> cd sftp_dir     
sftp> put abc-5.5.0.jar    
Uploading abc-5.5.0.jar to /sftp_dir/abc-5.5.0.jar

I want a shell script so that I can execute all these commands at a go, but I don't know how to hardcode ([email protected] and password ) in shell script.

The shell script which I wrote now is:

for f in *.jar
do  
    cp -v "$f" /home/webapps/project1/folder2/"${f%.jar}"$(date +%m%d%y).jar  
done 

Inside these script, I'm just copying the files to another location.

I need a shell script to do mv the jars from one server to another server like the sftp command mentioned above.

Upvotes: 1

Views: 3664

Answers (2)

Paul Hodges
Paul Hodges

Reputation: 15418

Use scp.

for f in *.jar
do  scp "$f" [email protected]:/home/webapps/project1/folder2/"${f%.jar}"$(date +%m%d%y).jar  
done 

If possible, set up a public key so that no password is required in your script. Good transfer systems like scp and sftp will be much easier to automate that way.

Upvotes: 3

ashish_k
ashish_k

Reputation: 1581

If you have the expect utility installed in your server, you could use it below way:

expect <<EOF
set timeout -1
spawn /usr/bin/sftp ${user_name}@${HOSTNAME}
expect "password:"
send "${passwd}\r"
expect "sftp>"
send "cd /the_path/to_put_files/\r"
expect "sftp>"
send "mput *\r"
expect "sftp>"
send "bye\r"
EOF

set timeout -1 == for sending n number of files to remote server without timeout constraint.

Hope this helps.

Upvotes: 1

Related Questions