Я могу войти в систему успешно своего облачного экземпляра как пользователь 'человечность' через SSH, но не могу войти в систему как пользователь 'корень'. Существует несколько сообщений, существующих касавшиеся изменения конфигурации ssh для предоставления корневого доступа, хотя ни один не работал от меня. Например, я внес обычные изменения в/etc/ssh/sshd_config файл, а именно:
#Authentication
PermitRootLogin yes
Это не имело никакого эффекта.
Теперь, сообщение, которое я получаю, когда я пытаюсь войти в систему как 'корень':
Войдите в систему как пользователь "человечность", а не пользователь "корень".
Grepping для "Войдите в систему", я нашел в '/usr/lib/python3/dist-packages/cloudinit/config/cc_ssh.py' файле (всех мест), следующие строки:
DISABLE_ROOT_OPTS = (
"no-port-forwarding,no-agent-forwarding,"
"no-X11-forwarding,command=\"echo \'Please login as the user \\\"$USER\\\""
" rather than the user \\\"root\\\".\';echo;sleep 10\"")
Я не могу сделать большую часть из этого. Я предполагаю, что этот скрипт Python был запущен, когда экземпляр был сначала создан и ответственен за некоторые дополнительные настройки SSH где-нибудь, которые блокируют меня от входа в систему как 'корень'.
Мне кажется, что оскорбление ssh конфигурационные директивы является 'no-X11-forwarding' и другими двумя. Я пришел к этому заключению, так как они, кажется, связаны с незаконным сообщением.
Я предполагаю что command
директива дает ssh демону команду показывать это сообщение, когда связанные директивы нарушены. Я на правильном пути?
Одна вещь, которую я должен добавить к этому, состоит в том, что я знаю об аргументах против входа в систему как пользователь root. Однако это - частный экземпляр, и я буду единственным пользователем. Мне нужен ssh доступ как 'корень', потому что скрипты развертывания, которые у меня есть потребность запустить как корень для предотвращения сложностей.
Обновление: сценарий Python, упомянутый ниже, является частью пакета Ubuntu CloudInit.
Дальнейшее обновление: Вот содержание/etc/pam.d/sshd файла...
# PAM configuration for the Secure Shell service
# Standard Un*x authentication.
@include common-auth
# Disallow non-root logins when /etc/nologin exists.
account required pam_nologin.so
# Uncomment and edit /etc/security/access.conf if you need to set complex
# access limits that are hard to express in sshd_config.
# account required pam_access.so
# Standard Un*x authorization.
@include common-account
# SELinux needs to be the first session rule. This ensures that any
# lingering context has been cleared. Without this it is possible that a
# module could execute code in the wrong domain.
session [success=ok ignore=ignore module_unknown=ignore default=bad] pam_selinux.so close
# Set the loginuid process attribute.
session required pam_loginuid.so
# Create a new session keyring.
session optional pam_keyinit.so force revoke
# Standard Un*x session setup and teardown.
@include common-session
# Print the message of the day upon successful login.
# This includes a dynamically generated part from /run/motd.dynamic
# and a static (admin-editable) part from /etc/motd.
session optional pam_motd.so motd=/run/motd.dynamic
session optional pam_motd.so noupdate
# Print the status of the user's mailbox upon successful login.
session optional pam_mail.so standard noenv # [1]
# Set up user limits from /etc/security/limits.conf.
session required pam_limits.so
# Read environment variables from /etc/environment and
# /etc/security/pam_env.conf.
session required pam_env.so # [1]
# In Debian 4.0 (etch), locale-related environment variables were moved to
# /etc/default/locale, so read that as well.
session required pam_env.so user_readenv=1 envfile=/etc/default/locale
# SELinux needs to intervene at login time to ensure that the process starts
# in the proper default security context. Only sessions which are intended
# to run in the user's context should be run after this.
session [success=ok ignore=ignore module_unknown=ignore default=bad] pam_selinux.so open
# Standard Un*x password updating.
@include common-password
... и содержание/etc/ssh/sshd_config файла...
# Package generated configuration file
# See the sshd_config(5) manpage for details
# What ports, IPs and protocols we listen for
Port 22
# Use these options to restrict which interfaces/protocols sshd will bind to
#ListenAddress ::
#ListenAddress 0.0.0.0
Protocol 2
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
#Privilege Separation is turned on for security
UsePrivilegeSeparation yes
# Lifetime and size of ephemeral version 1 server key
KeyRegenerationInterval 3600
ServerKeyBits 1024
# Logging
SyslogFacility AUTH
LogLevel INFO
# Authentication:
LoginGraceTime 120
PermitRootLogin yes
StrictModes yes
RSAAuthentication yes
PubkeyAuthentication yes
#AuthorizedKeysFile %h/.ssh/authorized_keys
# Don't read the user's ~/.rhosts and ~/.shosts files
IgnoreRhosts yes
# For this to work you will also need host keys in /etc/ssh_known_hosts
RhostsRSAAuthentication no
# similar for protocol version 2
HostbasedAuthentication no
# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication
#IgnoreUserKnownHosts yes
# To enable empty passwords, change to yes (NOT RECOMMENDED)
PermitEmptyPasswords no
# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication yes
# Change to no to disable tunnelled clear text passwords
PasswordAuthentication yes
# Kerberos options
#KerberosAuthentication no
#KerberosGetAFSToken no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
#UseLogin no
#MaxStartups 10:30:60
#Banner /etc/issue.net
# Allow client to pass locale environment variables
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication. Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM yes
... согласно просьбе.
Это настоятельно рекомендовано для блокирования удаленный root
войдите в сервер (соображения безопасности).
Рекомендуемый путь состоит в том, чтобы войти в систему как обычный пользователь и использование sudo
для получения root
доступ.
Окончательное sudo
команда, которая будет, предоставляет Вам полный root
доступ для каждой команды:
sudo bash
Для определенной команды, которая должна быть выполнена как root
можно использовать:
sudo specific-command
Пример для команды, которая будет выполняться как root
:
sudo ls -lsa /root
Примечание: Если Вы хотите изменить политику амазонки и разрешение root
вход в систему, Вы используете ответы от amazon-ec2-root-login ТАК Вопросы и ответы
Обратитесь к следующему для установки корневого входа в систему:
sudo -s (to become root) vi /root/.ssh/authorized_keys
Удалите строки в начале файла, пока Вы не доберетесь до слов
ssh-rsa
.vi /etc/ssh/sshd_config
Установите переменную
PermitRootLogin
кому:PermitRootLogin without-password
(без кавычек)sudo /etc/init.d/sshd restart
Взгляните на /root/.ssh/authorized_keys
файл. Скорее всего, Вы найдете что-то вроде этого:
root@instance-00:~# cat /root/.ssh/authorized_keys
no-port-forwarding,no-agent-forwarding,no-X11-forwarding,command="echo 'Please login as the user \"ubuntu\" rather than the user \"root\".';echo;sleep 10" ssh-rsa AAAA...= user@host
(Это было взято от другого облачного поставщика, но конфигурация, кажется, идентична Amazon).
Просто удалите все перед ssh-rsa
и необходимо смочь войти в систему как корень удаленно (конечно, все, что другие люди уже сказали Вам об этом, не быть лучшей практикой все еще применяется!)
Если Вы действительно ленивы, можно просто перезаписать authorized_keys
файл с помощью того от ubuntu
пользователь:
root@instance-00:~# cp /home/ubuntu/.ssh/authorized_keys /root/.ssh/authorized_keys
И на всякий случай Вам любопытно на предмет того, как тот префикс добрался там, тот же код Python, который Вы уже нашли (/usr/lib/python3/dist-packages/cloudinit/config/cc_ssh.py
) имеет ответ в apply_credentials
. Отметьте, как это устанавливает префикс для авторизованных ключей:
if disable_root:
if not user:
user = "NONE"
key_prefix = disable_root_opts.replace('$USER', user)
else:
key_prefix = ''