user393267
user393267

Reputation:

how to script commands that will be executed on a device connected via ssh?

So, I've established a connection via ssh to a remote machine; and now what I would like to do is to execute few commands, grab some files and copy them back to my host machine.

I am aware that I can run

ssh user@host "command1; command2;....command_n"

and then close the connection, but how can I do the same without use the aforememtioned syntax? I have a lot of complex commands that has a bunch of quote and characters that would be a mess to escape.

Thanks!

Upvotes: 1

Views: 1173

Answers (3)

jb62
jb62

Reputation: 2474

From here: Can I ssh somewhere, run some commands, and then leave myself a prompt?

The use of an expect script seems pretty straightforward... Copied from the above link for convenience, not mine, but I found it very useful.

#!/usr/bin/expect -f
spawn ssh $argv
send "export V=hello\n"
send "export W=world\n"
send "echo \$V \$W\n"
interact

I'm guessing a line like

send "scp -Cpvr someLocalFileOrDirectory [email protected]/home/you

would get you your files back...

and then:

send "exit"

would terminate the session - or you could end with interact and type in the exit yourself..

Upvotes: 0

salva
salva

Reputation: 10244

Instead of the shell use some scripting language (Perl, Python, Ruby, etc.) and some module that takes care of the ugly work. For example:

#!/usr/bin/perl
use Net::OpenSSH;
my $ssh = Net::OpenSSH->new($host, user => $user);
$ssh->system('echo', 'Net::Open$$H', 'Quot%$', 'Th|s', '>For', 'You!');
$ssh->system({stdout_file => '/tmp/ls.out'}, 'ls');
$ssh->scp_put($local_path, $remote_path);
my $out = $ssh->capture("find /etc");

Upvotes: 0

jane arc
jane arc

Reputation: 594

My immediate thought is why not create a script and push it over to the remote machine to have it run locally in a text file? If you can't for whatever reason, I fiddled around with this and I think you could probably do well with a HEREDOC:

ssh -t [email protected] bash << 'EOF'
command 1 ...
command 2 ...
command 3 ...

EOF

and it seems to do the right thing. Play with your heredoc to keep your quotes safe, but it will get tricky. The only other thing I can offer (and I totally don't recomend this) is you could use a toy like perl to read and write to the ssh process like so:

open S, "| ssh -i ~/.ssh/host_dsa -t [email protected] bash";
print S "date\n"; # and so on

but this is a really crummy way to go about things. Note that you can do this in other languages.

Upvotes: 1

Related Questions