Linux sh скрипт ssh

write a shell script to ssh to a remote machine and execute commands

The remote machines are VMs created on the run and I just have their IPs. So, I cant place a script file beforehand in those machines and execute them from my machine.

I think of deploying an agent-like program in remote Linux machines, which maintain connection with server by network socket ( or SSL ) connection / by periodic polling to server.

«no scripts» means «no files at all», I suppose? How do you handle authentication? You can disable the host fingerprint checking (see my answer), but you still get an interactive password prompt if you have not setup a public/private key.

Andreas: yes. no files at all. the passwd prompt can be handled using expect as ` expect «?assword:» `

10 Answers 10

There are multiple remote linux machines, and I need to write a shell script which will execute the same set of commands in each machine. (Including some sudo operations). How can this be done using shell scripting?

You can do this with ssh, for example:

#!/bin/bash USERNAME=someUser HOSTS="host1 host2 host3" SCRIPT="pwd; ls" for HOSTNAME in $ ; do ssh -l $ $ "$" done 

When ssh’ing to the remote machine, how to handle when it prompts for RSA fingerprint authentication.

You can add the StrictHostKeyChecking=no option to ssh:

ssh -o StrictHostKeyChecking=no -l username hostname "pwd; ls" 

This will disable the host key check and automatically add the host key to the list of known hosts. If you do not want to have the host added to the known hosts file, add the option -o UserKnownHostsFile=/dev/null .

Note that this disables certain security checks, for example protection against man-in-the-middle attack. It should therefore not be applied in a security sensitive environment.

what about if you also want to do a CTRL+C and continue ssh to multiple servers?. for example in some servers is asking for password and in some other no, so script will get stuck there . is there a way of doing somethong similar to -o for doing a CTRL c or CTRL d?

Читайте также:  My backbox linux with

I can execute a script from a sh file on the remote machine with this help: cat execute-remotely.sh | ssh server

Install sshpass using, apt-get install sshpass then edit the script and put your linux machines IPs, usernames and password in respective order. After that run that script. Thats it ! This script will install VLC in all systems.

#!/bin/bash SCRIPT="cd Desktop; pwd; echo -e 'PASSWORD' | sudo -S apt-get install vlc" HOSTS=("192.168.1.121" "192.168.1.122" "192.168.1.123") USERNAMES=("username1" "username2" "username3") PASSWORDS=("password1" "password2" "password3") for i in $ ; do echo $ SCR=$> sshpass -p $ ssh -l $ $ "$" done 

Syntax : ssh -i pemfile.pem user_name@ip_address ‘command_1 ; command 2; command 3’

#! /bin/bash echo "########### connecting to server and run commands in sequence ###########" ssh -i ~/.ssh/ec2_instance.pem ubuntu@ip_address 'touch a.txt; touch b.txt; sudo systemctl status tomcat.service' 

I was looking to execute a command on the remote machine, and this sample script with the remote command right after the ssh command on the same line helped. Thanks.

There are a number of ways to handle this.

My favorite way is to install http://pamsshagentauth.sourceforge.net/ on the remote systems and also your own public key. (Figure out a way to get these installed on the VM, somehow you got an entire Unix system installed, what’s a couple more files?)

With your ssh agent forwarded, you can now log in to every system without a password.

And even better, that pam module will authenticate for sudo with your ssh key pair so you can run with root (or any other user’s) rights as needed.

You don’t need to worry about the host key interaction. If the input is not a terminal then ssh will just limit your ability to forward agents and authenticate with passwords.

You should also look into packages like Capistrano. Definitely look around that site; it has an introduction to remote scripting.

Individual script lines might look something like this:

ssh remote-system-name command arguments . # so, for exmaple, ssh target.mycorp.net sudo puppet apply 

The accepted answer sshes to machines sequentially. In case you want to ssh to multiple machines and run some long-running commands like scp concurrently on them, run the ssh command as a background process.

#!/bin/bash username="user" servers=("srv-001" "srv-002" "srv-002" "srv-003"); script="pwd;" for s in "$"; do echo "sshing $@$ to run $" (ssh $@$ $)& # Run in background done wait # If removed, you can run some other script here 

There is are multiple ways to execute the commands or script in the multiple remote Linux machines. One simple & easiest way is via pssh (parallel ssh program)

Читайте также:  Linux генерация ключа rsa

pssh: is a program for executing ssh in parallel on a number of hosts. It provides features such as sending input to all of the processes, passing a password to ssh, saving the output to files, and timing out.

Example & Usage:

Connect to host1 and host2, and print «hello, world» from each:

 pssh -i -H "host1 host2" echo "hello, world" 

Run commands via a script on multiple servers:

Usage & run a command without checking or saving host keys:

pssh -h hostname_ip.txt -x '-q -o StrictHostKeyChecking=no -o PreferredAuthentications=publickey -o PubkeyAuthentication=yes' -i 'uptime; hostname -f' 

If the file hosts.txt has a large number of entries, say 100, then the parallelism option may also be set to 100 to ensure that the commands are run concurrently:

pssh -i -h hosts.txt -p 100 -t 0 sleep 10000 

Options:
-I: Read input and sends to each ssh process.
-P: Tells pssh to display output as it arrives.
-h: Reads the host’s file.
-H : [user@]host[:port] for single-host.
-i: Display standard output and standard error as each host completes
-x args: Passes extra SSH command-line arguments
-o option: Can be used to give options in the format used in the configuration file.(/etc/ssh/ssh_config) (~/.ssh/config)
-p parallelism: Use the given number as the maximum number of concurrent connections
-q Quiet mode: Causes most warning and diagnostic messages to be suppressed.
-t: Make connections time out after the given number of seconds. 0 means pssh will not timeout any connections

When ssh’ing to the remote machine, how to handle when it prompts for RSA fingerprint authentication.

Disable the StrictHostKeyChecking to handle the RSA authentication prompt.
-o StrictHostKeyChecking=no

Source: man pssh

Источник

Запуск команд или скрипта через SSH

Сегодня рассмотрим примеры для запуска команд или скрипта через SSH соединения. Научимся запускать наши команды/скрипты из одной рабочей станции Linux на другой удаленной Linux машине. Рассмотрим практические примеры использования мощного инструмента SSH в администрировании Linux.

Читайте также:  Linux консоль копирование папки

Запуск команд через SSH

Если вы хотите удаленно запустить какую-либо команду на сервере через SSH, то нет ничего проще. Давайте рассмотрим пару примеров.

Узнайте аптайм удаленного сервера:

Узнать проходит ли пинг на удаленном сервере до google DNS:

ssh root@10.5.5.1 'ping 8.8.8.8 -c 5'

Перезагрузить удаленную машину:

Запуск нескольких команд через SSH

В большинстве случаем недостаточно удаленно запустить только одну команду по SSH. Намного чаще необходимо отправить сразу несколько команд на удаленный сервер, например, для сбора информации и получить результат обратно.

Запустить несколько команд на удаленном хосте по SSH:

ssh ПОЛЬЗОВАТЕЛЬ@СЕРВЕР 'КОМАНДА1; КОМАНДА2; КОМАНДА3'

Практические примеры использования SSH

Узнайте аптайм и сколько свободного места на диске:

ssh root@10.5.5.1 'uptime; df -h'

Сколько используется памяти и среднюю нагрузку:

ssh root@10.5.5.1 'free -m ; cat /proc/loadavg'

Узнать версию ядра, количество ядер CPU и сколько всего RAM:

SSH: Запуск Bash Скрипта

Также бывает ситуация, когда на Linux сервере лежит какой-либо скрипт и его необходимо запустить по SSH на другом Linux сервере.

Основная идея заключается в том, чтобы подключиться на удаленный Linux сервер, дать скрипту выполнить свою работу и получить результат, при этом не копируя сам скрипт на удаленный сервер.

Эта задаче безусловно может быть выполнена и при этом довольно просто.

Что если вы хотите выполнить сценарий с аргументом.

Если требуются привилегии sudo, то команда примет вид:

ssh root@10.5.5.1 'echo "passwords" | sudo -Sv && bash -s' < script.sh
  • password — пароль для пользователя root на удаленной машине.
  • script.sh — файл с вашим скриптом расположенный на станции с которой производите подключение.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

network-logo

В этой статье рассмотрим пример как можно переименовать сетевые интерфейсы в дистрибутивах Linux. После обновления systemd (частью которого является udev) Читать

backup-wordpress

В этой статье я расскажу, как настроить резервное копирование с помощью ssh и cron в Linux дистрибутивов. Как нетрудно догадаться, Читать

network-logo

Сегодня в статье рассмотрим опции сервиса networking в Debian подобных системах таких как Ubuntu, Linux Mint, Elementary OS и т.д. Читать

kvm-logo

Не удалось подключиться к libvirt. Требуется установить openssh-askpass или аналогичную программу для соединения с этим узлом. Вот такое сообщение у Читать

Источник

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