Jessesiu
Jessesiu

Reputation: 151

Shell repeat execute ssh and scp command

I have two line need to repeat doing in for loop

ssh [email protected] mkdir -p $location
scp -r $i [email protected]:$location

but each time it need to input password, how can i change code then just need input one time or more fast way

Upvotes: 0

Views: 2067

Answers (2)

anishsane
anishsane

Reputation: 20980

While public/private keys is the easiest option, without need to change the existing script, there is another option, of using sshfs. sshfs may not be installed by default.

With this approach, you basically mount the remote file system to a local directory, over ssh protocol. Then you can simply use commands like mkdir / cp etc.

NOTE: These command are from YOUR system & not from REMOTE system.

Mounting over ssh is a one time job, which will require your manual intervention. Do this before running the script.
e.g. for your case:

mkdir /tmp/tam_192.168.174.43
sshfs [email protected]:/ /tmp/tam_192.168.174.43
[email protected]'s password: <ENTER PASSWORD HERE>

& then, in your script, use simple commands like:

mkdir -p /tmp/tam_192.168.174.43/$location
cp -r $i /tmp/tam_192.168.174.43/$location

& to unmount:

fusermount -u /tmp/tam_192.168.174.43

Upvotes: 0

Kumar Vikramjeet
Kumar Vikramjeet

Reputation: 263

You can use public/private key generation method using ssh-keygen (https://help.ubuntu.com/community/SSH/OpenSSH/Keys) And then use the below script.

for VARIABLE in dir1 dir2 dir3
do
ssh [email protected] mkdir -p $location
scp -r $i [email protected]:$location
done 

Alternative solution : You can use sshpass

for VARIABLE in dir1 dir2 dir3
do
ssh [email protected] mkdir -p $location sshpass -p '<password>' <command>
scp -r $i [email protected]:$location sshpass -p '<password>' <command>
done

Upvotes: 1

Related Questions