0

I want to ssh to multiple server using bash script and automate this script using crontab. I use "expect" to ssh to multiple server because of authentication need. But, I don't know how to copy the file in destination server using SFTP to my server. Can someone give me some clue for this problem.

Here is my code to SSH to multiple server (in this case I make tunneling to server destination):

/home/users/script/expect.sh 45108 username password "command" 
/home/users/script/expect.sh 45109 username password "command"
#45108 is port for tunneling, username and password is using like in shell terminal (ssh username@ipadd -p $server)

and this is the expect script that I use:

#!/usr/bin/expect
set timeout 10
set node [lindex $argv 0]
set username [lindex $argv 1]
set password [lindex $argv 2]
set command [lindex $argv 3]


spawn ssh $username@localhost -p $node
 expect {
 "(yes/no)?"
  {
  send "yes\n"
  expect "*assword:" { send "$password\n"}
 }
 "*assword:" { send "$password\n" }
 }

 expect {
 "*#" { send "$command\n" }
 }

expect {
 "*#" { send "exit\n" }
 }

expect eof

Thank you

  • Do you want to `scp` *instead of* `ssh`, or should both happen? In what sequence? Repurposing your expect script to use `scp` instead of `ssh` should be completely trivial, though the prompts etc will differ. – tripleee Jan 04 '19 at 08:07
  • if we use "sshpass", is it already ssh to remote server ?... and as you know, I need to upload the file to my server and with one script I need to ssh to multiple remote server. is it possible? @MartinPrikryl – Kresna Lita Jan 04 '19 at 08:27
  • I do not understand what you mean by *"if we use "sshpass", is it already ssh to remote server"*. – Martin Prikryl Jan 04 '19 at 08:28
  • sorry I'm newbie at bash script. I will read about ssh and scp. Thanks for your clue @tripleee – Kresna Lita Jan 04 '19 at 08:34
  • Thank you :) @MartinPrikryl for your clue. I will read it more deep. I just learn bash script in 2 weeks. – Kresna Lita Jan 04 '19 at 08:36

1 Answers1

-1
  1. Add your servers in ~/.ssh/config with use syntax:

```

Host server1
    HostName 192.168.1.10

Host server2
    HostName 192.168.1.11

```

  1. Create ssh key: ssh-keygen,
  2. Add your public key ~/.ssh/rsa.pub to ~/.ssh/authorized_keys on server.

Now, you can send file by use scp: scp file.zip server1:~/ https://nerderati.com/2011/03/17/simplify-your-life-with-an-ssh-config-file/

Mikołaj
  • 59
  • 6
  • Thanks for your answer. But, I already make a tunnel and what I want to know is sftp and in your answer is using scp right. So, I think it's clear. – Kresna Lita Jan 04 '19 at 08:41
  • Ok, maybe this: `rsync -av -e "sshpass -f '/tmp/pass.txt' ssh -o StrictHostKeyChecking=no" . USER@HOST:backups/ > /dev/null`. Write password in file `/tmp/pass.txt` before `echo "pass" > /tmp/pass.txt`. This is solve for problem with password auth. – Mikołaj Jan 04 '19 at 08:51
  • 1
    *Why* `sftp` instead of `scp`? ugh... – Paul Hodges Jan 04 '19 at 14:38