Vini.g.fer
Vini.g.fer

Reputation: 11909

Execute command inside a shell script on a remote machine and get output on local machine

There are similar questions on stackoverflow, but they either don't have an answer or use some language (C#, Python, ...). I'm trying to execute a command on a remote machine using ssh and get the console output back to the local machine. Below is the command I'm having issues:

sshpass -p $password 'find /home/pi/Transmission_Downloads/ -type f \( -iname "*.mp4" -o -iname "*.mkv" -o -iname "*.avi" \) -newermt "2016-02-01"' [email protected]

When I try to execute it inside my script I get "sshpass: Failed to run command: No such file or directory" error.

What I'm trying to achieve: fetch from the server a list of new files downloaded (movies and TV shows) for later on pulling them from the server using rsync.

Is there a way I can achieve this using only password, or do I HAVE TO use public/private keys to access the server?

My local machine is using Ubuntu 14.04 (desktop) and my server is running Raspbian.

Upvotes: 0

Views: 738

Answers (1)

Swami Moksha
Swami Moksha

Reputation: 486

Setting up a password less login to your remote machine might be a solution for easily accomplishing the task.

First log in on Sys_A as user a and generate a pair of authentication keys. Do not enter a passphrase:

a@Sys_A:~> ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/a/.ssh/id_rsa): 
Created directory '/home/a/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/a/.ssh/id_rsa.
Your public key has been saved in /home/a/.ssh/id_rsa.pub.
The key fingerprint is:
3e:4f:05:79:3a:9f:96:7c:3b:ad:e9:58:37:bc:37:e4 a@A

Now use ssh to create a directory ~/.ssh as user b on Sys_B. (The directory may already exist, which is fine):

a@Sys_A:~> ssh b@B mkdir -p .ssh
b@Sys_B's password: 

Finally append a's new public key to b@Sys_B:.ssh/authorized_keys and enter b's password one last time:

a@Sys_A:~> cat .ssh/id_rsa.pub | ssh b@B 'cat >> .ssh/authorized_keys'
b@Sys_B's password:

From now on you can log into Sys_B as b from Sys_A as a without password:

a@Sys_A:~> ssh b@Sys_B

Then you can integrate your command in a bash script, and use ssh without any user interaction.

Upvotes: 1

Related Questions