Ssh user password linux

Pass a password to ssh in pure bash

I want to pass a password to ssh using a bash script (Yes, I know that there are ssh keys that I could use, but this is not what I intend). I found some solutions that were using expect but since it is not a standard bash tool I am wondering if I can do this using pipes. Can someone explain to me, why exactly something like this:

echo "password\n" | ssh somehost.com 

doesn’t work? Is there any possibility to make it work? Maybe executing ssh as a different process, obtaining its PID and then sending a string directly to it?

Though this question may sound off topic for stackoverflow, I didn’t found it being asked anywhere else. The question and answer helped me understanding that, WHY the pipe didn’t work for ssh. («printf user/pass | vpn user@HOST» works. )

3 Answers 3

You can not specify the password from the command line but you can do either using ssh keys or using sshpass as suggested by John C. or using a expect script.

To use sshpass, you need to install it first. Then

instead of using sshpass -p your_password . As mentioned by Charles Duffy in the comments, it is safer to supply the password from a file or from a variable instead of from command line.

From a security perspective, passwords should never be passed on a command line — command lines are visible to the entire system; even commands that change their command line after they started are vulnerable to capture in the interim. There are other, much safer usage patterns for sshpass if you must use that tool.

You might demonstrate sshpass -f <(printf '%s\n' your_password) ssh user@hostname in the answer, to have a better-practice approach highly visible. (Because printf is a shell builtin, it doesn't get executed as a separate command with its argv exposed via procfs).

$ brew search sshpass . We won’t add sshpass because it makes it too easy for novice SSH users to ruin SSH’s security. That’s comprehensive. Don’t do noninteractive passwords. Do SSH keys.

Since there were no exact answers to my question, I made some investigation why my code doesn’t work when there are other solutions that works, and decided to post what I found to complete the subject.
As it turns out:

«ssh uses direct TTY access to make sure that the password is indeed issued by an interactive keyboard user.» sshpass manpage

which answers the question, why the pipes don’t work in this case. The obvious solution was to create conditions so that ssh «thought» that it is run in the regular terminal and since it may be accomplished by simple posix functions, it is beyond what simple bash offers.

Since you ended up linking to sshpass I think you should have given the other guy credit for the answer.

I suggest you to first read what the question was, instead of adding comments that bring nothing to the topic.

Читайте также:  Kaspersky для linux сертификат

If your question is genuinely only about why thing-X doesn’t work, your title should reflect that, as opposed to being about how to accomplish the goal that thing-X would otherwise be performing. Right now, the body of the question focuses on that area, but the title is all about accomplishing the task.

@CharlesDuffy How does «pure bash» does not reflect the need to use standard bash calls? What kind of mental workout have you done to come to such conclusion?

@BłażejMichalik, . so, the point I’ve been making is that the title should have reflected the question’s intent given in the body. I don’t object to the OP’s intent not to rely on tools not specified by POSIX, built into bash, or provided as part of the SSH package. I do object to their question’s title being a poor fit to that question’s intent.

If you need to use password authentication then more secure is to send the password from a password vault to your clipboard and then just paste it when prompted by ssh. In the following script a credential is passed to a password vault pass and then any additional arguments are passed to ssh. You can use the following script in other scripts to further automate ssh use.

#!/bin/bash USAGE="USAGE: passtossh credential . " [[ $# -lt 2 ]] && echo "$USAGE" && exit 64 CRED="$1" shift echo "Creating a ssh connection using credentials $CRED with parameters $@ ." echo "$(pass "$CRED")" | tr -d '\n' | pbcopy ssh $@ 

You can use this script like this (for example ssh to a host along with any additional parameters):

$ passtossh my_credential user@host -L 8888:localhost:8888 

and when prompted just paste the password. Pbcopy is MacOS utility for sending stdin to clipboard. For windows clip , for linux see for example link.

Benefit is that password will not appear in logs and also the password can only be accessed by whatever authentication you have for the password vault.

Источник

How to specify password in ssh command

From the terminal I type: ssh user@ip and then it prompts for a password.
Is there a way to specify the password in the ssh command itself?

2 Answers 2

sshpass -ffilename ssh user@ip # prefer this sshpass -pPa5sw0rd ssh user@ip # avoid this 

where your password is in the first line of the file filename or it is literally Pa5sw0rd . Notes:

  • In the manual there is no space after -p or -f , but at least sshpass 1.06 in my Debian 10 allows it; your sshpass may or may not.
  • If your password contains characters your shell will interpret (like $ , ‘ or ; ) then you should quote it properly in the command line (but not in the file).
  • Avoid -p . Use chmod 600 filename to make the file private (root will still be able to access it though). Read about security considerations in the manual.

Any solution for macOS? sshpass isn’t part of the default OS, and doesn’t seem to be available in Homebrew either.

The correct way to do this, is to switch from password authentication to a public/private key pair. This typically needs no reconfiguration at all and is quite easy.

Читайте также:  How to rise linux

Step 1: If you do not have a key, create one: ssh-keygen will do that for you

Step 2: Authorize this key on the remote host: Run ssh-copy-id user@ip once, using your password

Step 3: From now on ssh user@ip will no longer ask for your password

Thats correct. But the servers that i am working with are currently having password based authentication. And its really irritating to type password each time they prompt

from a security perspective this is the correct way to do it. but the OP asked «How to specify password in ssh command».

Nearly ALL servers allow key authentication in addition to password authentication — so you use the password authentication (via ssh-copy-id ) to enable the key.

Источник

Как подключиться к серверу по SSH с помощью пароля или ключа

Как подключиться к серверу через SSH

SSH — зашифрованный протокол для удаленного управления серверами. Для подключения через него вы можете каждый раз вводить пароль или настроить авторизацию по ключу. Второй вариант безопаснее, но у него есть свои особенности. В этой статье мы рассмотрим оба метода подключения, а вы уже сами выберите, какой способ удобнее.

Проверка службы SSH на сервере

Доступ по SSH обычно можно включить при создании сервера или во время настройки конфигурации. Убедиться в том, что он разрешен, можно через консоль. Она доступна в панели управления сервером.

Например, у меня VDS на Timeweb. Чтобы попасть в консоль, я авторизуюсь по логину и паролю, выданному хостером, выбираю свой сервер в списке VDS и перехожу на вкладку «Консоль».

Вход в консоль

Чтобы пользоваться консолью, нужно авторизоваться. Логин и пароль для доступа к серверу хостер присылает в письме. Сначала нужно ввести логин и нажать на клавишу Enter. Появится строка Password. В ней необходимо ввести пароль и снова нажать на клавишу Enter.

Важно: в целях безопасности при вводе пароля на экране не отображаются никакие символы, даже привычные звездочки.

После авторизации в консоли можно проверить, запущена ли служба SSH на сервере.

  1. Выполните команду systemctl status sshd.
  2. Обратите внимание на строчку Active. В ней должна быть выделенная зеленым запись active (running). Это состояние говорит о том, что служба запущена.

Служба SSH работает

Если служба не активна, добавьте ее самостоятельно. Выполните команду sudo apt install openssh-server и подтвердите установку пакетов.

Кроме того, для подключения вам может понадобиться настройка брандмауэра. Чтобы межсетевой экран не блокировал входящие соединения, можно на время отключить его командой sudo ufw disable.

Использование пароля

Начнем с инструкции о том, как подключиться к удаленному серверу через SSH по логину и паролю. Это самый простой способ. Хостер предоставляет вам IP-адрес, логин и пароль. Этого достаточно для того, чтобы установить соединение с удаленным сервером.

Подключение на Windows

Моя основная система — Windows. Раньше для подключения к серверу через SSH я пользовался сторонней утилитой PuTTY, потому что в операционной системе не было встроенного компонента. В «десятке» он появился, так что теперь можно подключаться к SSH через командную строку (cmd).

Чтобы включить встроенный в систему OpenSSH:

  1. Откройте «Параметры» (Win + I) и перейдите в раздел «Приложения».
  2. Выберите опцию «Управление дополнительными компонентами».
  3. Нажмите «Добавить компонент».
  4. Выберите в списке OpenSSH Client и нажмите «Установить».
  5. После завершения установки перезагрузите систему.
Читайте также:  Linux postgresql failed to start

Клиент OpenSSH на Windows

Теперь разберемся, как подключиться к SSH через cmd. Запустите командную строку и выполните запрос вида ssh root@185.104.114.90.

Значение root — логин для подключения, вы получили его в письме при создании сервера. 185.104.114.90 — IP-адрес сервера. Его можно посмотреть в панели управления сервером или в том же письме, которое прислал хостер. У команды может быть также дополнительный параметр -p, после которого прописывается номер порта. По умолчанию используется порт 22. Если у вас настроен другой порт, нужно явно его указать, — например, полный адрес может выглядеть так: ssh root@185.104.114.90 -p 150.

После выполнения команды клиент SSH предложит добавить устройство в список известных. Введите в командной строке yes и нажмите на Enter. Затем укажите пароль для доступа к серверу. На этом подключение к серверу через SSH завершено — теперь все команды будут выполняться на удаленной машине, к которой вы подключились.

На версиях младше Windows 10 1809 нет встроенной поддержки протокола OpenSSH. В таком случае понадобится сторонняя утилита. Смотрим, как через PuTTY подключиться по SSH:

  1. Запустите PuTTY.
  2. На вкладке Session укажите Host Name (IP-адрес сервера), Port (по умолчанию 22, но если вы в конфигурации сервера указали другой порт, нужно задать его номер).
  3. Убедитесь, что тип соединения установлен SSH.
  4. Нажмите на кнопку Open, чтобы подключиться.

SSH в программе PuTTY

Если вы ввели правильные данные, появится окно консоли, в котором нужно указать логин и пароль для подключения к серверу. При первом запуске также отобразится запрос на добавление устройства в список известных.

Подключение на Linux и macOS

Теперь посмотрим, как подключиться по SSH через терминал на Linux. Для этого не требуется установка дополнительных компонентов, все работает «из коробки».

  1. Запустите терминал. Обычно для этого используется сочетание клавиш Ctrl+Alt+T. Найти терминал также можно по пути «Главное меню» — «Приложения» — «Система».
  2. Выполните команду для подключения. Синтаксис такой же, как на Windows, — ssh root@ 185.104.114.90 . Если порт не стандартный, то нужно явно его указать: например, ssh root@ 185.104.114.90 -p 150. Вместо root вы указываете свое имя пользователя, а вместо 185.104.114.90 — IP-адрес своего сервера.
  3. Если хост и порт указаны верно, на следующем шаге появится запрос на ввод пароля. При первом подключении также будет предложение добавить новое устройство в список известных. Для этого введите yes и нажмите на клавишу Enter.

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

Если IP-адрес или порт указаны неверно, то на экране появится сообщение об ошибке — Connection Refused. Это может также говорить о том, что доступ запрещен брандмауэром на удаленном сервере (если вы его не отключили). Чтобы разрешить подключение через SSH:

  • на сервере с Ubuntu/Debian выполните команду $ sudo ufw allow 22/tcp;
  • на сервере CentOS/Fedora выполните команду $ firewall-cmd —permanent —zone=public —add-port=22/tcp.

Цифра 22 в синтаксисе — номер порта. Если вы используете другой порт, то укажите его явно.

Если вы знаете как подключиться через SSH на Linux, то справитесь с этой задачей и на macOS. В операционной системе Apple тоже есть встроенный терминал. Синтаксис команды для подключения не меняется: ssh root@ 185.104.114.90 , где root — ваш логин, а 185.104.114.90 — IP-адрес сервера, с которым вы устанавливаете соединение.

Источник

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