Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging in via a script to a remote server and execute a set of commands

How can I login to a remote server and execute a set of commands then when done logout and continue my script?

Thanks.

like image 380
emurad Avatar asked Jun 04 '11 20:06

emurad


People also ask

How do you connect to a remote server and execute some commands?

The SSH client program can be used for logging into a remote machine or server and for executing commands on a remote machine. When command is specified, it is executed on the remote host/server instead of a login shell.


2 Answers

ssh can be used to execute a command, rather than start a remote interactive login shell. For example:

ssh user@host ls

Will log into host and execute the ls command.

You can use this inside a bash script as normal:

#!/bin/bash

# do local commands

ssh user@host "ls; grep something file.txt; copy a b"

# do more local commands

From ssh's man page, the exit status will be the exit status of the remove command or 255 if an error occurred.

like image 155
Louis Marascio Avatar answered Oct 08 '22 21:10

Louis Marascio


Small variation with easier code formatting using ssh and bash -s:

echo '
globchar="*"
ls -1d $globchar
ls -ld $globchar
' |
ssh user@host "bash -s --"
like image 37
acolo Avatar answered Oct 08 '22 21:10

acolo