9

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

Thanks.

1
  • 1
    Don't put Perl as a keyword unless you have a Perl question Commented Jun 5, 2011 at 12:43

3 Answers 3

12

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.

Sign up to request clarification or add additional context in comments.

6 Comments

A few options: (1) place the commands in a separate file, use scp to copy the commands to the remote server, and run it or (2) put the commands into a variable inside the bash script and just run it as ssh user@host "$COMMAND". You could read from a file into COMMAND rather than have it all inline: COMMAND=$(cat remote_cmds.sh)
Why these aren't working: ssh [email protected] "EEEEE='eeeesssse' echo '$EEEEE' echo \"$EEEEE\""
@emurad: You need to separate the commands with semicolons and you should reverse double and single quotes to keep the local shell away from $EEEEE: ssh [email protected] 'EEEEE='eeeesssse';echo "$EEEEE";echo "$EEEEE"'
I followed your first suggestion and it worked very well (scp). Thanks.
Alternatively, separating the commands by newlines would work, too. Not sure how you can use this in perl, though.
|
1

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

echo '
globchar="*"
ls -1d $globchar
ls -ld $globchar
' |
ssh user@host "bash -s --"

Comments

1

As others have stated, you can use ssh. However, if you're running a script, you may want to setup ssh to login without a password. You can do that by setting up a public/private key via the ssh-keygen command. Also change the permission of keyfiles (id_rsa, id_rsa.pub) as 600 for public key and 400 for private key for security of modification. chmod 600 id_rsa.pub ;chmod 400 id_rsa

On your system, you run ssh-keygen to generate the public and private keys. On Unix/Linux/Mac, these sit in the $HOME/.ssh directory. (Keep the passphrase blank!). Then, you want to create a file called authorized_keys on the remote machine under the $HOME/.ssh directory and copy your public key there.There is no need of generating encryption keys on remote m/c.

Now, when you do ssh or scp to the remote machine, you don't have to give the password.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.