Ssh from linux to linux command

SSH Command — Usage, Options, Configuration

Practically every Unix and Linux system includes the ssh command. This command is used to start the SSH client program that enables secure connection to the SSH server on a remote machine. The ssh command is used from logging into the remote machine, transferring files between the two machines, and for executing commands on the remote machine.

Contents

SSH Command in Linux

The ssh command provides a secure encrypted connection between two hosts over an insecure network. This connection can also be used for terminal access, file transfers, and for tunneling other applications. Graphical X11 applications can also be run securely over SSH from a remote location.

Other SSH Commands

There are other SSH commands besides the client ssh . Each has its own page.

ssh-keygen — creates a key pair for public key authentication

ssh-copy-id — configures a public key as authorized on a server

ssh-agent — agent to hold private key for single sign-on

ssh-add — tool to add a key to the agent

scp — file transfer client with RCP-like command interface

sftp — file transfer client with FTP-like command interface

Using the Linux client

Linux typically uses the OpenSSH client. The ssh command to log into a remote machine is very simple. To log in to a remote computer called sample.ssh.com, type the following command at a shell prompt:

If this is the first time you use ssh to connect to this remote machine, you will see a message like:

Type yes to continue. This will add the server to your list of known hosts (

/.ssh/known_hosts ) as seen in the following message:

Each server has a host key , and the above question related to verifying and saving the host key, so that next time you connect to the server, it can verify that it actually is the same server.

Once the server connection has been established, the user is authenticated. Typically, it asks for a password. For some servers, you may be required to type in a one-time password generated by a special hardware token.

Once authentication has been accepted, you will be at the shell prompt for the remote machine.

Specifying a different user name

It is also possible to use a different username at the remote machine by entering the command as:

The above can also be expressed with the syntax:

Executing remote commands on the server

The ssh command is often also used to remotely execute commands on the remote machine without logging in to a shell prompt. The syntax for this is:

For example, to execute the command:

on host sample.ssh.com, type the following command at a shell prompt:

After authenticating to the remote server, the contents of the remote directory will be displayed, and you will return to your local shell prompt. -x Disables X11 forwarding.

SSH client configuration file

The ssh command reads its configuration from the SSH client configuration file

/.ssh/config . For more information, see the page on SSH client configuration file .

Configuring public key authentication

To configure passwordless public key authentication , you may want to create an SSH key and set up an authorized_keys file. See the pages on ssh-keygen and ssh-copy-id for more information.

Configuring port forwarding

Command-line options can be used to set up port forwarding. Local fowarding means that a local port (at the client computer) is tunneled to an IP address and port from the server. Remote forwarding means that a remote port (at the server computer) is forwarded to a given IP address and port from the client machine. See the page on configuring port forwarding on how to configure them.

OpenSSH also supports forwarding Unix domain sockets and IP packets from a tunnel device to establish a VPN (Virtual Private Network).

SSH command line options

Some of the most important command-line options for the OpenSSH client are:

-1 Use protocol version 1 only.

-2 Use protocol version 2 only.

-4 Use IPv4 addresses only.

-6 Use IPv6 addresses only.

-A Enable forwarding of the authentication agent connection.

-a Disable forwarding of the authentication agent connection.

-C Use data compression

-c cipher_spec Selects the cipher specification for encrypting the session.

-D [bind_address:] port Dynamic application-level port forwarding. This allocates a socket to listen to port on the local side. When a connection is made to this port, the connection is forwarded over the secure channel, and the application protocol is then used to determine where to connect to from the remote machine.

-E log_file Append debug logs to log_file instead of standard error.

-F configfile Specifies a per-user configuration file. The default for the per-user configuration file is

-g Allows remote hosts to connect to local forwarded ports.

-i identity_file A file from which the identity key (private key) for public key authentication is read.

-J [user@] host [:port] Connect to the target host by first making a ssh connection to the pjump host[(/iam/jump-host) and then establishing a TCP forwarding to the ultimate destination from there.

-l login_name Specifies the user to log in as on the remote machine.

Читайте также:  Removing windows install files

-p port Port to connect to on the remote host.

-V Display the version number.

-X Enables X11 forwarding.

A little history

SSH replaced several older commands and protocols in Unix and Linux the 1990s. The include telnet , rlogin , and rsh .

SSH runs at TCP/IP port 22. This is right between ftp and telnet, which are 20 years older. Read the story of how SSH got port 22 .

The following video summarizes how and why SSH was originally developed.

Together with our customers, our mission is to secure their digital business on on-premises, cloud, and hybrid ecosystems cost-efficiently, at scale, and without disruptions to their operations or business continuity.

Источник

SSH: Execute Remote Command or Script – Linux

This is quite a common task for Linux system administrators, when it is needed to execute some command or a local Bash script from a one Linux workstation or a server on another remote Linux machine over SSH.

In this article you will find the examples of how to execute a remote command, multiple commands or a Bash script over SSH between remote Linux hosts and get back the output (result).

This information will be especially useful for ones, who want to create a Bash script that will be hosted locally on a one Linux machine but would be executed remotely on the other hosts over SSH.

Cool Tip: Connect to a remote SSH server without typing a password! Configure a passwordless authentication! Only 3 easy steps! Read more →

SSH: Execute Remote Command

Execute a remote command on a host over SSH:

Examples

Get the uptime of the remote server:

Reboot the remote server:

SSH: Run Multiple Remote Commands

Much more often it is required to send multiple commands on a remote server, for example, to collect some data for inventory and get back the result.

There are a lot of different ways of how it can be done, but i will show the most popular of them.

Run multiple command on a remote host over SSH:

Cool Tip: SSH login is too slow? This can be fixed easily! Get rid of delay during authentication! Read more →

Examples

Get the uptime and the disk usage:

Get the memory usage and the load average:

Show the kernel version, number of CPUs and the total RAM:

SSH: Run Bash Script on Remote Server

The idea is to connect to a remote Linux server over SSH, let the script do the required operations and return back to local, without need not to upload this script to a remote server.

Certainly this can be done and moreover quite easily.

Cool Tip: Want to ROCK? Start a GUI (graphical) application on a remote Linux workstation over SSH! Read more →

Example

Execute the local script.sh on the remote server:

20 Replies to “SSH: Execute Remote Command or Script – Linux”

Nice Post there..I was wondering what if want to execute the script with an argument.

Hi,
How about executing a command remotely and making sure that it will be killed once i kill my ssh session. or getting of PID of either SSH or the actual command on remote-node via a script.
Something like this I want to achieve:
Example: collecting pcap on remote addr and storing it locally.

I was unable to get the proper Pids in this case. Any reply would be helpful.

How to check remote server services which require sudo privilege?

How to check remote server services which require sudo privilege from local script file?

is what I use to send a bash script over the wire with sudo priviliges

How do create a scrip to run commands on multiple remote machines?
When the first one gets executed, the response returned to STOUT, and the next one is not executed until I ^C the previous command.
I tried using ‘exit’ command and ‘&’ , neither is working.

useless writing! Where it’s remote script executing example about sudo use?

Hello everyone,
I am new to linux and trying to learn it. I have task to complete “Get last 3 login details of list of linux machine with date and time.”
Is there any way to achive it?

Thanks in advance

Command $backdoor
$bash -0 $(wich bash)
Whoami..
#root

You should change these examples to use double quotes – I got tripped up putting variables in these single quotes and took me a while to realise bash treats it as a string…

como puedo hacer que solo me pida una vez la contraseña de mi servidor? hice mi escript y como realizo varias tareas me pide varias veces la contraseña

usa ssh-copy-id para copiar la llave

This was very helpful !
Thanks 🙂

Can someone help me write a shell script to shutdown a Ubuntu computer?
I’m going to have it run on a Mac, so that it will ssh into the Ubuntu and shut it down. I need it to open Application “Terminal” then ssh name@123.45.67.89, then give it the password.
Then I need it to issue command “sudo poweroff”, and give it the password again.
I know how to do this manually by opening Mac’s Terminal. I just type in “ssh name@123.456.78.9, it asks for the password, I type it in, and it’s connected. Then I just type in “sudo poweroff” and it asks for the password again, I type it in, and bam, it shuts down the Ubunt computer.
The problem is, I need to automate this to do it at a specific time of day. On the Mac, there is what is called “Automator”, and you can set up ICalendar Events to run an “Automator Workflow” with a Shell Script. I just don’t know how to write the Shell Script to do what I can do manually? Any help is appreciated greatly!

I solved this. Here’s what works:
tell application “Terminal”
activate
do script (“ssh test@192.168.1.10“)
delay 6
do script “password” in front window
delay 7
do script “sudo poweroff” in front window
delay 5
do script “password” in front window
end tell

Источник

How to Use SSH Command in Linux

SSH is a popular, powerful, software-based approach to network security. It is used for logging into a remote machine and for executing commands on a remote machine. Whenever data is sent by a computer to the network, ssh will automatically encrypt it. It is designed and created to provide the best security when accessing another computer remotely. SSH server, by default, listens on the standard TCP port 22.

Читайте также:  Выбрать канал wifi mac os

To use SSH, the destination machine should have a SSH server application installed because SSH is a client-server model.

In this guide, we will learn about SSH command, configuration, usage and options on Linux system to help you connect to a remote server.

Installing SSH

Modern Linux should have installed SSH by default. If it’s not, we can install it manually. The easiest way to install SSH is through your Linux package manager.

On Ubuntu/Debian

Install ssh-client

Install ssh-server

On RedHat/CentOS

Once SSH is installed we can check it by typing ssh from your Linux console.

1) SSH Commands

Run SSH without no options

A common way to use SSH is without any options. Just type “ssh ”. Here’s a sample :

When the first time you connect to a destination host, ssh will confirm you about the authenticity of the destination host. If you answer No, then SSH will not continue while if you said Yes, SSH will continue.

The next time you login into the same host, SSH will not ask you a confirmation. The authenticity oft the host by default is saved under /home/user/.ssh folder in every user.

Specify a username for login

By default, ssh will try to connect using active user as a username. On the previous command, ssh will try to login into the server using a username named ‘pungki’. This is because user ‘pungki’ on the client side, is running ssh client.

What about if in the destination host, there is no user named ‘pungki’? Then you must supply a username that exist in the destination host. To specify the username from the beginning, use -l option

We can also type like this :

Specify the port

SSH default port is 22. Most modern Linux has port 22 open. If you run ssh without defining a port, then ssh will direct the request via port 22.

But some system administrator may change the default SSH port. Let say that the port now is 1234. To contact that host, use -p option followed by SSH port.

To change the port number, we need to modify the /etc/ssh/ssh_config.

Change it into another port, for example above, is 1234. Then restart the SSH service.

Request compression on every data

With this option, all data which sent and received via SSH will be compressed. The data still encrypted. To use compression with SSH, use -C option.

This option will be useful if your connection is slow, such as using a modem. But when you are using a fast connection such as LAN or higher, than compression will be slow down your transfer rate.

The level of compression can be controlled using -o option followed by CompressionLevel option. But this option will only applied for SSH-1.

Define a cipher algorithm

SSH provides some cipher algorithms to be used. These algorithms can be seen inside /etc/ssh/ssh_config or

/.ssh/config file (if exist).

Let say you want to use blowfish algorithm for encrypting your SSH session. Then you can put this line into your /etc/ssh/ssh_config or

By default, SSH will use 3des algorithm

Turn on debug mode

When we are not able to connect to the remote host, it is good to debug and find the exact error messages that causing the issue. Use the -v option for debugging the ssh client.

Bind source address

If your client has more than 2 IP Address, you might not know which IP Address is used to create a connection to the SSH server.

To solve this situation, we can use b option which will bind an IP Address to SSH connection. This IP Address will be used as the source address of the connection.

On the server side, we can check the established connection to the server using netstat. We see that 192.168.0.200 connection is established.

Change the default configuration file

By default, ssh will use ssh configuration file which located in /etc/ssh/ssh_config. This file is applied to system wide. If you want to apply the particular setting to the specific user, you should put it in

/.ssh/config file. If you don’t see it, you can create it.

Here’s a sample of a custom ssh_config. This config is located in /home/pungki directory.

To use a specific config file, we can use -F option.

Use SSH X11 Forwarding

There are three types of port forwarding with SSH:

1. Local port forwarding : connections from the SSH client are forwarded via the SSH server, then to a destination server

2. Remote port forwarding : connections from the SSH server are forwarded via the SSH client, then to a destination server

3. Dynamic port forwarding : connections from various programs are forwarded via the SSH client, then via the SSH server, and finally to several destination servers

Local Port Forwarding

This would forward two connections, one to 172.18.19.23, the other to 172.18.19.20. Pointing your browser at http://localhost:8080/ would download pages from 172.18.19.23, and pointing your browser to http://localhost:12345/ would download pages from 172.18.19.20.

Remote Port Forwarding

The -R option specifies remote port forwarding. For the duration of the SSH session, ec2-52-66-84-114.ap-south-1.compute.amazonaws.com would be able to access your desktop by connecting a VNC client to port 5900 on his computer (if you had set up a shared desktop)

Dynamic Port Forwarding

The -D option specifies dynamic port forwarding. 1001 is the standard SOCKS port. Although you can use any port number, some programs will only work if you use 1001. -C enables compression, which speeds the tunnel up when proxying mainly text-based information (like web browsing), but can slow it down when proxying binary information (like downloading files).

Next, you would tell Firefox to use your proxy:

Forwarding GUI Programs

Once the connection is made, type the name of your GUI program on the SSH command-line:

Trusted X11 Forwarding

If you pretty sure that your network is secure, then you may want to use Trusted X11 Forwarding. This mean that the remote X11 clients will have full access to the original X11 display. To use this option, we can use -Y option.

Читайте также:  Не работает pkg kali linux

2) SSH Options

Lets check what all are the ssh options available.

StrictHostKeyChecking

If you would like to bypass this verification step, you can set the «StrictHostKeyChecking» option to «no» on the command line.

This option disables the prompt and automatically adds the host key to the

ConnectTimeout

I’m executing a script connecting via password-less SSH on a remote host. I want to set a timeout, so that if the remote host is taking an infinite time to run, I want to comeout of that ssh session and continue other lines in my sh script.

BatchMode

If you use ssh -o “BatchMode yes”, and password less connectivity is enable the command execute successfully on remote, else it will return error and continues.

Batch mode command execution using SSH — success case

[Note: This will display the output of remote-host’s who command]

Batch mode command execution using SSH — Failure case

Note: If you didn’t use -o “BatchMode yes”, the above command would’ve asked for the password for my account on the remote host. This is the key difference in using the BatchMode yes option.

Bind IP Example

Find the version of the SSH command

We can find the version of SSH installed on the unix system using the -V option to the ssh.

This is shown below:

-v option for run ssh command in Verbose mode.

Causes ssh to print debugging messages about its progress. This is helpful in debugging connection, authentication, and configuration problems. Multiple -v options increase the verbosity and the maximum is 3.

3) SSH Config with Examples

There is two main configuration files for SSH.

/.ssh/config ( Per-user’s configuration file )

This file is used by the SSH client. this file must have strict permissions: read/write for the user, and not accessible by others. We use all parameter in this file for accessing another computer remotely. This files called client configuration files

/etc/ssh/ssh_config ( system-wide configuration file )

This file provides defaults for those values that are not specified in the user’s configuration file, and for those users who do not have a configuration file. This file must be world-readable. all parameter defined in this file world-readable.

SSH Config File options

The /etc/ssh/ssh_config file is the system-wide configuration file for Open SSH which allows you to set options
that modify the operation of the client programs. The file contains keyword-value pairs, one per line, with keywords being case insensitive.
Here are the most important keywords to configure your ssh for top security.

Description of config file parameter

The option Host restricts all forwarded declarations and options in the configuration file to be only for those hosts that match one of the patterns given after the keyword. The pattern * means for all hosts up to the next Host keyword. With this option, you can set different declarations for different hosts in the same ssh_config file.

The option ForwardAgent specifies which connection authentication agent if any should be forwarded to the remote machine.

The option ForwardX11 is for people that use the Xwindow GUI and want to automatically redirect X11 sessions to the remote machine. Since we setup a server and don’t have GUI installed on it, we can safely turn this option off.

The option RhostsAuthentication specifies whether we can try to use rhosts based authentication. Because rhosts authentication is insecure you shouldn’t use this option.

The option RhostsRSAAuthentication specifies whether or not to try rhosts authentication in concert with RSA host authentication.

The option RSAAuthentication specifies whether to try RSA authentication. This option must be set to yes for better security on your sessions. RSA uses public and private keys pair created with the ssh-keygen1utility for authentication purposes.

The option PasswordAuthentication specifies whether we should use password-based authentication. For strong security. This option must always be set to yes. this parameter protect your server connectivity to other
without password no one connect to server.

The option FallBackToRsh specifies that if a connection with ssh daemon fails rsh should automatically be used instead. Recalling that rsh service is insecure, this option must always be set to no.

The option UseRsh specifies that rlogin/rsh services should be used on this host. As with the FallBackToRsh option, it must be set to no for obvious reasons.

The option BatchMode specifies whether a username and password querying on connect will be disabled. This option is useful when you create scripts and dont want to supply the password. e.g. Scripts that use the scp command to make backups over the network.

The option CheckHostIP specifies whether or not ssh will additionally check the host IP address that connect to the server to detect DNS spoofing. It’s recommended that you set this option to yes.

The option StrictHostKeyChecking specifies whether or not ssh will automatically add new host keys to the $HOME/.ssh/known_hosts file, or never automatically add new host keys to the host file. This option, when set to yes, provides maximum protection against Trojan horse attacks. One interesting procedure with this option is to set it to no at the beginning, allow ssh to add automatically all common hosts to the host file as they are connected to, and then return to set it to yes to take advantage of this feature.

The option IdentityFile specifies an alternate RSA authentication identity file to read. Also, multiple identity files may be specified in the configuration file ssh_config.

The option Cipher specifies what cipher should be used for encrypting sessios. The blowfish use 64-bit blocks and keys of up to 448 bits.

The option EscapeChar specifies the session escape character for suspension.

Sample Configuration file for testing with parameter

We have create /export/oracle/db/config/ssh/config.922pw using multiple parameter for testing .

When we try to connect remote server with our configuration files , all parameter call in ssh connectivity.
Please find the below out of ssh connectivity with config file .

Conclusion

As usual, we can always type man ssh and man ssh_config to display its manual pages and explore more detail. Hope you enjoyed reading and please leave your suggestions in the below comment section.

Источник

Оцените статью