Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use ssh in a shell script?

Tags:

bash

shell

ssh

ksh

rsh

When I try to use an ssh command in a shell script, the command just sits there. Do you have an example of how to use ssh in a shell script?

like image 920
Jon Ericson Avatar asked Aug 26 '08 22:08

Jon Ericson


People also ask

What is SSH in shell script?

SSH, also known as Secure Shell or Secure Socket Shell, is a network protocol that gives users, particularly system administrators, a secure way to access a computer over an unsecured network. SSH also refers to the suite of utilities that implement the SSH protocol.

Can I SSH in a bash script?

Bash script SSH is a common tool for Linux users. It is needed when you want to run a command from a local server or a Linux workstation. SSH is also used to access local Bash scripts from a local or remote server.

How do I run a command using SSH?

Run the command "ssh username@host" to log in to the system. At the command prompt, run "top" to view process activity on the remote system. Exit top and be dropped to the remote command line. Type "Exit" to close the command.

How do I open an SSH shell?

You can start an SSH session in your command prompt by executing ssh user@machine and you will be prompted to enter your password. You can create a Windows Terminal profile that does this on startup by adding the commandline setting to a profile in your settings.


2 Answers

Depends on what you want to do, and how you use it. If you just want to execute a command remotely and safely on another machine, just use

ssh user@host command

for example

ssh user@host ls

In order to do this safely you need to either ask the user for the password during runtime, or set up keys on the remote host.

like image 173
Mats Fredriksson Avatar answered Oct 06 '22 07:10

Mats Fredriksson


First, you need to make sure you've set up password-less (public key login). There are at least two flavors of ssh with slightly different configuration file formats. Check the ssh manpage on your system, consult you local sysadmin or head over to How do I setup Public-Key Authentication?.

To run ssh in batch mode (such as within a shell script), you need to pass a command you want to be run. The syntax is:

ssh host command

If you want to run more than one command at the same time, use quotes and semicolons:

ssh host "command1; command2"

The quotes are needed to protect the semicolons from the shell interpreter. If you left them out, only the first command would be run remotely and all the rest would be run on the local machine.

like image 41
Jon Ericson Avatar answered Oct 06 '22 07:10

Jon Ericson