- How to shutdown / reboot the remote Linux server from the CLI
- How to reboot the remote Linux server
- How to shutdown the remote Linux server
- Use IPMI to shutdown/reboot server
- SSH: Execute Remote Command or Script – Linux
- SSH: Execute Remote Command
- Examples
- SSH: Run Multiple Remote Commands
- Examples
- SSH: Run Bash Script on Remote Server
- Example
- 20 Replies to “SSH: Execute Remote Command or Script – Linux”
- Run a script on remote host without caring ssh session
- 2 Answers 2
- Методы удаленного доступа к Linux GUI
- Введение
- Установка GUI
- Удаленный доступ
- TeamViewer
How to shutdown / reboot the remote Linux server from the CLI
First, you need to ssh into the remote box and issue the following commands.
How to reboot the remote Linux server
The syntax is:
ssh user@server-name-here
Type the following command to reboot the box:
sudo reboot
Another option is:
ssh -t vivek@server1.cyberciti.biz ‘sudo reboot’
OR use the shutdown command:
ssh -t vivek@server1.cyberciti.biz ‘sudo shutdown -r 0’
OR
ssh -t vivek@server1.cyberciti.biz ‘sudo shutdown -r now ‘
Sample outputs:
You must pass the -t option to the ssh command to force pseudo-terminal allocation. The shutdown accepts -r option i.e. Linux is rebooted at the specified time. A value of zero indicates reboot the machine immediately.
How to shutdown the remote Linux server
The syntax is:
ssh user@server-name-here
Type the following command to reboot the box:
sudo halt
Another option is:
ssh -t vivek@server1.cyberciti.biz ‘sudo halt’
OR use the shutdown command:
ssh -t vivek@server1.cyberciti.biz ‘sudo shutdown -h 0’
OR
ssh -t vivek@server1.cyberciti.biz ‘sudo shutdown -h now ‘
You must pass the -t option to the ssh command to force pseudo-terminal allocation. The shutdown accepts -h option i.e. Linux is powered/halted at the specified time. A value of zero indicates poweroff the machine immediately.
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Use IPMI to shutdown/reboot server
The Intelligent Platform Management Interface (IPMI) allows you to control power of your server using the CLI or web interface. For example one can login to IPMI web interface and issue the command:
Fig.01: Use IPMI to perform a power control operation on your server
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
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
Источник
Run a script on remote host without caring ssh session
I have a python script in a folder of a remote machine. For executing it, I make a ssh session from my local computer, go to that folder and run.
Now the problem is ssh session. The script takes lot of time and due to internet issues, ssh session terminates and script doesn’t complete. Assume that the remote is always up and running.
Can I run the script without caring of the ssh session termination and do tail -f abc.log with ssh anytime I want ?
$ python abc.py >> abc.log & , then you can hit enter and control+d to exit the ssh manually and script would keep running.
2 Answers 2
You can run the script either in a screen or can run the process in nohup+bg. I always prefer Screen but let me explain both methods.
You can use nohup command to run a process by detaching from terminal like this nohup python /my/folder/abc.py & This by default creates nohup.out file where all the logs will be stored. If you want custom file then you can use redirection then it will be nohup python /my/folder/abc.py >> abc.log &
In single command it will be
From the docs.
Screen is a full-screen window manager that multiplexes a physical terminal between several processes, typically interactive shells. Each virtual terminal provides the functions of the DEC VT100 terminal and, in addition, several control functions from the ISO 6429 (ECMA 48, ANSI X3.64) and ISO 2022 standards (e.g. insert/delete line and support for multiple character sets). There is a scrollback history buffer for each virtual terminal and a copy-and-paste mechanism that allows the user to move text regions between windows.
When screen is called, it creates a single window with a shell in it (or the specified command) and then gets out of your way so that you can use the program as you normally would. Then, at any time, you can create new (full-screen) windows with other programs in them (including more shells), kill the current window, view a list of the active windows, turn output logging on and off, copy text between windows, view the scrollback history, switch between windows, etc. All windows run their programs completely independent of each other. Programs continue to run when their window is currently not visible and even when the whole screen session is detached from the user’s terminal.
So you can directly run the script in screen using ssh and then you can view the logs whenever needed either by attaching to screen or you can redirect the logs to some file directly or redirect to both file and out put using tee.
Run command in screen and print output in stdout(terminal).
Run command in screen and redirect output to file.
Run command in screen and redirect output to both file as well as to stdout(terminal).
Note: In all the above commands exec bash is needed else the screen will terminate once the job complets.
Any one of the above commansd should do the job.
In all the above cases you can attach the screen ScreenName using screen -r ScreenName and can see the logs.
I always recommend stderr redirection when redirecting to a file.
Источник
Методы удаленного доступа к Linux GUI
В службу технической поддержки RUVDS регулярно обращаются по поводу GUI и удаленного доступа к нему на виртуальных серверах с Linux, несмотря на то что в интернете достаточно много материалов освещающих эту проблему. Поэтому, для наших пользователей мы решили собрать всё по этой теме в одну статью.
Введение
На всякий случай возможно стоит упомянуть, что SSH — основной способ предоставления доступа к линуксовым виртуалкам на RUVDS. Большая часть действий описываемых в этой статье будет осуществляться именно таким образом.
Для подключения необходимо найти SSH-клиент для вашей операционной системы.
- OpenSSH; если Вы пользуетесь Linux, например Ubuntu, скорее всего всё уже установлено, до нас, так что можно смело писать в терминале: ssh root@[IP].
- PuTTY есть и для Linux, в том числе в официальных репозиториях Debian и Ubuntu.
MAC OS:
Установка GUI
Итак, перейдем к установке GUI. Сначала нужно поставить графическую подсистему:
Для Debian/Ubuntu:
Далее следует установка Desktop Environment (DE). Их существует великое множество. Мы рекомендуем ставить на сервер более легковесные среды, а еще лучше, не ставить вовсе. Первые две DE достаточно компактные, функциональные и «привычные».
1. Xfce
Для Debian/Ubuntu:
Можно поставить дополнительно:
Добавление русской раскладки:
Сочетание клавиш можно менять на свое усмотрение, например:
Чтобы эта команда запускалась каждый раз при запуске LXDE, нужно добавить в конец файла с помощью вашего любимого vi строку: @setxkbmap -option grp:switch,grp:ctrl_shift_toggle,grp_led:scroll us,ru. Или вот так…
Следующие две DE являются чрезвычайно легкими. Если уж GUI нужен на сервере, вероятно, стоит использовать именно их.
3. FluxBox
Для Debian/Ubuntu:
4. Openbox
Для Debian/Ubuntu:
Далее следуют наиболее популярные на десктопах графические оболочки.
5. Gnome
Для Ubuntu/Debian:
Замечание: с настройкой VNC-сервера под Gnome что-то пошло не так… Сервера из репозиториев tightvncserver и vnc4server так и не согласились сотрудничать, поэтому пришлось собрать пару deb-пакетов руками. Если у Вас не получится настроить сервер, то мы можем порекомендовать скачать собранный нами архив с tigervnc-server’ом и поставить его. Для этого:
7. Cinnamon
Для Debian/Ubuntu:
Если Вы хотите получать доступ к GUI через «Аварийный режим», то необходимо сделать следующее:
Мало того, необходимо обеспечить запуск графической оболочки при старте системы. Для этого можно установить какой-нибудь экранный менеджер (Display Manager, DM), например:
Или в случае с CentOS:
Если необходимости в доступе из личного кабинета нет, то следует выполнить:
Заметка: Ubuntu предлагает своим пользователям несколько метапакетов для более удобной установки нужной DE:
Далее, есть много способов получить удаленный доступ к GUI.
Удаленный доступ
На виртуальном сервере, в зависимости от OS нужно произвести следующие действия.
Далее, если вы используете Windows, подключаемся через встроенный RDP-клиент, Remote Desktop Connection (Подключение к удаленному рабочему столу).
Стандартный порт 3389. Для Linux есть масса клиентов которые можно установить из репозиториев: freerdp и remmina, gnome-rdp, vinagre и т.п.
Также можно пробросить RDP-шный трафик через SSH-туннель. Для этого нужно поправить конфигурационный файл xrdp:
В секцию [globals] нужно добавить строку: address=127.0.0.1
Проверить, что всё правильно, можно так:
Затем если вы используете cygwin или mingw, linux или mac os:
Запустите PuTTY. В древовидном меню слева Connection → SSH → Tunnels. Далее добавляем новый Forwarded Port (Source port: 3389, Destination: localhost:3389). Нажимаем Add.
Далее следуете в секцию Session. Вводите IP вашего сервера в поле Host Name (or IP address). Нажимаете кнопку Open, вводите пароль для подключения по SSH.
Далее для Windows:
- Можно использовать вышеупомянутый клиент: remmina
- Если в браузере хотите: novnc — HTML5 VNC client
- И ещё куча всяких разных: directvnc, gnome-rdp, krdc, xtightvncviewer, vinagre, xvnc4viewer
Для MAC OS:
OS X предоставляет для этого встроенное приложение Screen Sharing. Можно также использовать Safari
Сервер: На Вашей виртуальной машине установите VNC сервер:
Если на Вашей системе работает файрвол необходимо открыть соответствующие порты. Пример для CentOS
При возникновении проблем с отображением иконок и шрифтов при использовании xfce4 по Ubuntu/Debian:
Если вы хотите, чтобы VNC-сервер стартовал автоматически, создайте файл:
Со следующим содержимым:
Теперь можно подключиться, например, через UltraVNC. Для этого нужно запустить UltraVNC Viewer, в поле VNC Server записать [IP]::5901 (по-умолчанию: 5901, 5902 и т.п. для первого дисплея, второго и т.д. соответственно) и нажать на кнопку подключиться.
Также можно пустить vnc-шный трафик через ssh-туннель. Для этого отредактируйте:
Затем если вы используете cygwin или mingw, linux или mac os:
Если PuTTY:
Запустите PuTTY. В древовидном меню слева Connection → SSH → Tunnels. Далее добавляем новый Forwarded Port (Source port: 5901, Destination: localhost:5901). Нажимаем Add.
Далее следуете в секцию Session. Вводите IP вашего сервера в поле Host Name (or IP address). Нажимаете кнопку Open, вводите пароль для подключения по SSH.
Затем открываете UltraVNC Viewer и в поле VNC Server вводите: localhost::5901 после чего подключаетесь.
Также можете попробовать другие VNC-сервера:
x11vnc — фактически VNC-сервер (как vnc4server или tightvnc), но позволяет получать доступ к уже существующей X-сессии. Т.е. если Вы настроили графическую оболочку таким образом, что она запускается при старте системы, то можно использовать следующий вариант:
После подключения по VNC (на порт 5900) Вы должны увидеть тоже что и в «Аварийном режиме».
Для старта x11vnc при запуске OS необходимо проделать следующее:
Теперь немного поинтереснее. Одна замечательная компания NoMachine разработала отличный протокол NX на замену VNC. Клиенты для подключения по этому протоколу бесплатны, а официальное серверное ПО от NoMachine стоит много денег. В свое время, эта же компания поддерживала проект FreeNX работы на котором со временем затихли; текущая версия 0.7.2 от 2008-08-22. Но, к счастью, нашлись люди создавшие форк и назвавшие его x2go. К сожалению, x2go не совместим ни с NX от NoMachine, ни с freeNX. Так что клиент берем тут.
Установка сервера на Debian (источник):
Для примера поставим эту DE:
Далее следуем инструкциям с оффициального сайта:
Вывод следующей команды должен показать, что x2go готов к работе:
А теперь важный момент, подключиться без этого фикса не получится! Нужно найти в файле .profile строку «mesg n» и заменить её на «tty -s && mesg n».
Следующая команда выведет путь до исполняемого файла startfluxbox, понадобится при настройке клиента:
Установка сервера на Ubuntu:
А теперь важный момент, подключиться без этого фикса не получится! Нужно найти в файле .profile строку «mesg n || true» и заменить её на «tty -s && mesg n».
Установка сервера на CentOS:
Клиент для линукс ставится из вышеприведенных репозиториев следующей командой:
Для Windows — скачиваем, ставим, запускаем. По той же ссылке, приведенной выше, есть клиент для OS X.
В настройках сессии указываем: в поле Host — IP вашего сервера, в поле Login — root, порт оставляем как есть, session type — тот GUI который ставили.
Как вы можете видеть, есть возможность аутентификации по ключу. В общем много всякого. Посмотрите сами. И звук можно через PulseAudio выводить.
После нажатия Ok вы увидите вот такие вот очаровательные штучки, на которые нужно нажать для получения запроса на ввод пароля и подключения к выбранной сессии:
Замечание: обратите внимание, что в списке нет Вашего любимого FluxBox’а поэтому путь к нему приходится прописывать руками.
Важной возможностью x2go является возможность запуска любого графического приложения вообще без установки DE. Для этого в настройках сессии нужно в секции session type нужно выбрать пункт single application и выбрать выполняемое приложение или ввести путь к программе которую следует запустить.
В этом случае установка ПО на сервер будет выглядеть следующим образом. В случае с Ubuntu:
А теперь важный момент, подключиться без этого фикса не получится! Нужно найти в файле .profile строку «mesg n || true» и заменить её на «tty -s && mesg n».
И настроив сессию как показано ниже, можно будет запустить браузер на удаленном сервере, а на вашей машине откроется окно его отображающее:
Или так; тогда просто откроется окно терминала:
Ниже вы можете видеть скриншот окна статуса текущей сессии. Оранжевыми цифрами отмечены кнопки:
- «Suspend session» — после нажатия на эту кнопку соединение будет разорвано, но сессия останется и будет ожидать повторного подключения. Все запущенные вами на сервере приложения продолжат свою работу;
- «Terminate session» — после нажатия подключение к серверу будет разорвано, а запущенные вами на сервере приложения будут завершены.
TeamViewer
Последний способ удаленного доступа к рабочему столу.
Установка на Ubuntu:
Установка на Debian:
Установка на CentOS:
Также необходимо принять лицензионное соглашение TeamViewer’а, это можно сделать с помощью «Аварийного режима», либо добавить следующие строки в конец файла /opt/teamviewer/config/global.conf:
Следующая команда покажет состояние демона TeamViewer’а и необходимый для подключения девятизначный TeamViewer ID:
После запуска клиента скачанного тут, нужно ввести TeamViewer ID в поле Partner UD и нажать на кнопку «Connect to partner». Далее TeamViewer запросит пароль: [PASSWD].
Источник