How Can I Log In As root User?
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | Yes |
Requirements | su/sudo |
Est. reading time | Less than a minute |
It is not good a practice for anyone to use root as their normal user account, because of security risks. Therefore, you use a normal user account instead. You need to use the su or sudo command to switch to root user account.
su command
The su command is use to change user ID or become super-user during a login session i.e. it allows you to become a super user or substitute user, spoof user, set user or switch user.
Note: su only works if you know the target or root user’s password.
su command syntax
If invoked without a user-name, su defaults to becoming the super user. The user will be prompted for a password, if appropriate.
To log in as root user type the following command (you need to supply root user account password when prompted):
$ su —
Sample outputs:
Once logged in, your prompt should change from $ to #. To log in as another user say nixcraft, type the following command (you need to supply nixcraft user account password when prompted):
$ su — nixcraft
Sample outputs:
Remote root login over the ssh session
You can use the ssh client as follows:
$ ssh root@server.ip-address-here
$ ssh root@server1.cyberciti.biz
$ ssh root@1.2.3.4
However, remote root login over ssh session is disabled in most cases for security reasons. First, login as a normal user and then switch to root account using the su command:
su command and log files
The su command logs its usage in a system log file. This is useful to find out su login information. If you are RHEL / CentOS / Fedora Linux user type the following as root to see the contents of /var/log/secure:
# tail -f /var/log/secure
Debian / Ubuntu Linux user try:
# tail -f /var/log/auth.log
Sample outputs:
Say hello to sudo command
The sudo is a program for Linux / Apple OS X / *BSD / Unix-like computer operating systems that allows users to run programs with the security privileges of another user, normally the superuser (root). By default, sudo will prompt for a user password but it may be configured to require the root password or no password at all. Apple Mac OS X and Ubuntu Linux and many other oses uses sudo command for many administrative tasks.
- 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 ➔
sudo executes a command as another user but follows a set of rules about which users can execute which commands as which other users. This is configured in a filed named /etc/sudoers. Unlike su, sudo authenticates users against their own password rather than that of the target user. See how to configure and use sudo tool under Linux operating system.
For example, to login as root under Linux or Unix like operating system, type:
$ sudo -s
Sample sudo command session
Fig.01: Switching to root account using sudo command
Sudo and log file
The sudo log can be viewed by issuing the following command as root user:
See also
- Linux Run Command As Another User – Explains how to run run Linux commands as another user or run commands as root user using runuser, su, and sudo utilities.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
I have installed ubuntu and always log in as user. I have read the HOW TOO’s but I am confused by the comment ‘Make sure you use the root password.’ How can you use a root password when you haven’t got one (I think) because the only password I use is the password I gave when I installed Ubuntu (dapper Drake). Is this a root password also if you say it’s root as time of login. If you have to have a seperate login root password – How do you get it? Thanks john6.
By default, the root account password is locked in Ubuntu. This means that you cannot login as root directly or use the su command to become the root user. However, since the root account physically exists it is still possible to run programs with root-level privileges.
Hmmm, lets see Can not log in as : \ SU Thought Ubuntu is open source The only why you can adjust the Kernel is as root. what they hiddin willis.
opp’s should have read more of the reply’s. but as a openBSD user never really had this issue.
Thank you very much for this help!
To all the latin people…..here is the answer in spanish:
Escriban “su -” para cambiar al root. Les pedira la clave del root.
Escriban “su – gon” para cambiar al usuario llamado gon. Les pedira la clave.
John.
You can change your root password by typing in console” sudo passwd root ” By doing this i had to enter my user password then set a new root password and repeat it.
Baller. That was perfect. Thank you.
thnx. by default there is no password for root, hve to get by typing ”sudo passwd root”.
Thanks for this article and to AIS/fahim for the additional information about how to change the root password! Just what I was looking for.
AIS, thanks a lot
The question is still unanswered.
To login as root is very convenience and very important for some applications. Without it, you may not be able to run those programs at all. Su is good but with great limitation.
So if anyone who know the answer, please help. We do not need advise about workaround.
After 5 minutes of browsing on the Internet, I found it is very easy to make the changes so you can login as root from GUI. This is for Fedora 11:
First, (dangerous?) you must su and login as root then cd to /etc/pam.d
There are two files: gdm and gdm-password. Use your editor and
Comment this statement for both files:
# auth required pam_succeed_if.so user != root quiet
Save and logout. Try login as root. You should be.
After login as root and play around, I found the above changes were not enough. Thanks to my-guides.net, I found the last piece that fixed the problem.
You need to edit another file: /etc/PolicyKit/PolicyKit.conf
and add
between .
That will do the job.
The missing statement between is
Thanks a tonnnnn Gregory. Somehow I could never find the answer for this , instead of getting ridiculed for wanting this. 🙂
Thanks for command “sudo passwd root” !!
you didn’t answer the question!
you condescendingly gave some “best practices” advice, and then proceeded to explain out how to do something else.
I have to agree that the entire tenor of this conversation is offensive. Crossing the street is dangerous, also, but I do it anyway. My mother taught me the risks when I was quite small, as well as how to do it safely. If you really want to keep UBUNTU safe from learning problems, I suggest that you lock down the entire system and send us all to a Windows app.
Instead, please stop insulting all of us who are adults and capable of taking our own risks. I need to open the folder /etc/openvpn using my GUI and add a file to the folder. Stop patronizing me and tell me how to do this please.
I agree whole-heartedly. Uber-geek Linux users can be extremely condescending. I’ve had them to tell me to RTFM. Which one? The “right” one”? The “other” one. The one that applies to my distro? Oh wait, that distro has tons of bugs, but the upcoming distro gives you a workaround. RTFM!
How bout this? FTFM ! FIX it. Fix all the crappy and conflicting documentation. Yeah, this thing is “free”. But when all the wasted time getting things to work is considered, it’s more expensive than products from The Dark Empire. Bottom line is, if you’re going to do something, whether it’s for free or not, do it right and make it work like you say it does. Or don’t do it at all.
You people have a lot of nerve criticizing Windows when you worship a product that is a stone’s throw away from hieroglyphics and documented in glyphs.
Cheers, ubers …
I agree wholeheartedly. I need Linux for a project, but it, and all other Linux distros I’ve used, seems to be dwelling in the past, and the developers delight in their backward approach and to delight in making things difficult. Personally, I think it’s almost up to the Windows 98 point, but not quite there yet….
Источник
Лог файлы Linux по порядку
Невозможно представить себе пользователя и администратора сервера, или даже рабочей станции на основе Linux, который никогда не читал лог файлы. Операционная система и работающие приложения постоянно создают различные типы сообщений, которые регистрируются в различных файлах журналов. Умение определить нужный файл журнала и что искать в нем поможет существенно сэкономить время и быстрее устранить ошибку.
Журналирование является основным источником информации о работе системы и ее ошибках. В этом кратком руководстве рассмотрим основные аспекты журналирования операционной системы, структуру каталогов, программы для чтения и обзора логов.
Основные лог файлы
Все файлы журналов, можно отнести к одной из следующих категорий:
Большинство же лог файлов содержится в директории /var/log .
- /var/log/syslog или /var/log/messages содержит глобальный системный журнал, в котором пишутся сообщения с момента запуска системы, от ядра Linux, различных служб, обнаруженных устройствах, сетевых интерфейсов и много другого.
- /var/log/auth.log или /var/log/secure — информация об авторизации пользователей, включая удачные и неудачные попытки входа в систему, а также задействованные механизмы аутентификации.
- /var/log/dmesg — драйвера устройств. Одноименной командой можно просмотреть вывод содержимого файла. Размер журнала ограничен, когда файл достигнет своего предела, старые сообщения будут перезаписаны более новыми. Задав ключ —level= можно отфильтровать вывод по критерию значимости.
- /var/log/alternatives.log — Вывод программы update-alternatives , в котором находятся символические ссылки на команды или библиотеки по умолчанию.
- /var/log/anaconda.log — Записи, зарегистрированные во время установки системы.
- /var/log/audit — Записи, созданные службой аудита auditd .
- /var/log/boot.log — Информация, которая пишется при загрузке операционной системы.
- /var/log/cron — Отчет службы crond об исполняемых командах и сообщения от самих команд.
- /var/log/cups — Все, что связано с печатью и принтерами.
- /var/log/faillog — Неудачные попытки входа в систему. Очень полезно при проверке угроз в системе безопасности, хакерских атаках, попыток взлома методом перебора. Прочитать содержимое можно с помощью команды faillog .
- var/log/kern.log — Журнал содержит сообщения от ядра и предупреждения, которые могут быть полезны при устранении ошибок пользовательских модулей встроенных в ядро.
- /var/log/maillog/ или /var/log/mail.log — Журнал почтового сервера, используемого на ОС.
- /var/log/pm-powersave.log — Сообщения службы экономии заряда батареи.
- /var/log/samba/ — Логи файлового сервера Samba , который используется для доступа к общим папкам Windows и предоставления доступа пользователям Windows к общим папкам Linux.
- /var/log/spooler — Для представителей старой школы, содержит сообщения USENET. Чаще всего бывает пустым и заброшенным.
- /var/log/Xorg.0.log — Логи X сервера. Чаще всего бесполезны, но если в них есть строки начинающиеся с EE, то следует обратить на них внимание.
Для каждого дистрибутива будет отдельный журнал менеджера пакетов.
- /var/log/yum.log — Для программ установленных с помощью Yum в RedHat Linux.
- /var/log/emerge.log — Для ebuild -ов установленных из Portage с помощью emerge в Gentoo Linux.
- /var/log/dpkg.log — Для программ установленных с помощью dpkg в Debian Linux и всем семействе родственных дистрибутивах.
И немного бинарных журналов учета пользовательских сессий.
- /var/log/lastlog — Последняя сессия пользователей. Прочитать можно командой last .
- /var/log/tallylog — Аудит неудачных попыток входа в систему. Вывод на экран с помощью утилиты pam_tally2 .
- /var/log/btmp — Еже один журнал записи неудачных попыток входа в систему. Просто так, на всякий случай, если вы еще не догадались где следует искать следы активности взломщиков.
- /var/log/utmp — Список входов пользователей в систему на данный момент.
- /var/log/wtmp — Еще один журнал записи входа пользователей в систему. Вывод на экран командой utmpdump .
И другие журналы
Так как операционная система, даже такая замечательная как Linux, сама по себе никакой ощутимой пользы не несет в себе, то скорее всего на сервере или рабочей станции будет крутится база данных, веб сервер, разнообразные приложения. Каждое приложения или служба может иметь свой собственный файл или каталог журналов событий и ошибок. Всех их естественно невозможно перечислить, лишь некоторые.
- /var/log/mysql/ — Лог базы данных MySQL.
- /var/log/httpd/ или /var/log/apache2/ — Лог веб сервера Apache, журнал доступа находится в access_log , а ошибки — в error_log .
- /var/log/lighthttpd/ — Лог веб сервера lighttpd.
В домашнем каталоге пользователя могут находится журналы графических приложений, DE.
/.xsession-errors — Вывод stderr графических приложений X11.
/.xfce4-session.verbose-log — Сообщения рабочего стола XFCE4.
Чем просматривать — lnav
Почти все знают об утилите less и команде tail -f . Также для этих целей сгодится редактор vim и файловый менеджер Midnight Commander. У всех есть свои недостатки: less неважно обрабатывает журналы с длинными строками, принимая их за бинарники. Midnight Commander годится только для беглого просмотра, когда нет необходимости искать по сложному шаблону и переходить помногу взад и вперед между совпадениями. Редактор vim понимает и подсвечивает синтаксис множества форматов, но если журнал часто обновляется, то появляются отвлекающие внимания сообщения об изменениях в файле. Впрочем это легко можно обойти с помощью .
Недавно я обнаружил еще одну годную и многообещающую, но слегка еще сыроватую, утилиту — lnav, в расшифровке Log File Navigator.
Установка пакета как обычно одной командой.
Навигатор журналов lnav понимает ряд форматов файлов.
- Access_log веб сервера.
- CUPS page_log
- Syslog
- glog
- dpkg.log
- strace
- Произвольные записи с временными отметками
- gzip, bzip
- Журнал VMWare ESXi/vCenter
Что в данном случае означает понимание форматов файлов? Фокус в том, что lnav больше чем утилита для просмотра текстовых файлов. Программа умеет кое что еще. Можно открывать несколько файлов сразу и переключаться между ними.
Программа умеет напрямую открывать архивный файл.
Показывает гистограмму информативных сообщений, предупреждений и ошибок, если нажать клавишу . Это с моего syslog-а.
Кроме этого поддерживается подсветка синтаксиса, дополнение по табу и разные полезности в статусной строке. К недостаткам можно отнести нестабильность поведения и зависания. Надеюсь lnav будет активно развиваться, очень полезная программа на мой взгляд.
Источник