- How to View Linux System Reboot Date and Time
- 1. Last command
- 2. Who command
- 3. Use the perl code snippet
- Linux Find Out Last System Reboot Time and Date Command
- Use who command to find last system reboot time/date
- Finding systems last shutdown date and time
- Find out Linux system up since…
- macOS (OS X)/Unix/FreeBSD find out last reboot and shutdown time command examples
- How do I find who rebooted/shutdown the Linux box?
- Conclusion
- Время последнего перезапуска системы Linux
How to View Linux System Reboot Date and Time
Question: From the uptime command, I know how many days and hours the system is up and running. Is there a easy way to view the exact date and time on when the system was last rebooted? i.e Exactly from what date and time the system has been up and running?
Answer: Uptime does give this information indirectly. In the following example, it indicates that the system has been up and running for “137 days, 6 hours and 13 minutes”. But, you can’t quickly calculate the exact reboot date and time from this.
Instead of saying the system has been up and running for the last “137 days, 6 hours and 13 minutes”, wouldn’t be nice if it says the system has been running since “Sat May 14 20:38” (or something like that)? That is exactly what any one of the following three method does.
1. Last command
Use the ‘last reboot’ command, which will display all the previous reboot date and time for the system. This picks the information from the /var/log/wtmp file.
2. Who command
Use the ‘who -b’ command which displays the last system reboot date and time.
3. Use the perl code snippet
If you insist on using the uptime output to calculate the last reboot time, you can do it manually, or use the following perl code-snippet.
In this example, the above code-snippet displayed the following output:
I don’t remember exactly from where I got the above perl code-snippet. But, that didn’t stop me from trying to figure out what it does. Let us take this opportunity to learn little perl. This is what the above perl code-snippet does:
- -n is perl command line option. Causes the perl program to loop over the input
- -e is perl command line option. Indicates that it is a perl one liner ( i.e perl will not expect a file name, something like “perl filename.pl”).
Following are the Regex used, and its explanations:
- .*up + – Match anything until the string “up” and one or more space, for matching the following from uptime output.
- (?:(\d+) days. +) – Single group
- (?:(\d+) days. +)? – Question mark followed by this group says that this group is optional
This part says, if there is a days part in uptime output, capture it, or ignore. The following breaks down the above group in detail.
- (?:pattern) – Non capturing parenthesis which is used to group, but don’t capture the matched to memory which is $1, $2 etc ..
- (\d+) – Match one or more digit and put it into $1 (because this is the first group)
- SPACE days? – Match the literal space followed by day or days
- ,? – comma is optional
- SPACE+ – one or more spaces
The following breaks down this pattern (\d+):(\d+),.*/
- (\d+) – Capture the hour part into $2
- : – Followed by colon
- (\d+) – Capture the minute part into $3
- , – Match comma
- .* – Match everything else
Following are the rest of the time function in the above perl code-snippet.
- $total=((($1*24+$2)*60+$3)*60) – Calculate the total amount of seconds the system is UP. i.e (((days*24+hours)*60+minutes)*60 which gives the seconds (like an epoch calculation)
- $now=time(); – Get the current time in seconds ( epoch time )
- $now-=$total; – Subtract total system running time from current time. So this is getting the exact time in second when the system was started
- $now=localtime($now); – Convert the epoch time ( time in seconds ). localtime returns given epoch time in human readable format
- print $now,”\n” – Finally, this prints the time.
Источник
Linux Find Out Last System Reboot Time and Date Command
Use who command to find last system reboot time/date
You need to use the who command, to print who is logged on. It also displays the time of last system boot. Use the last command to display system reboot and shutdown date and time, run:
$ who -b
Sample outputs:
Use the last command to display listing of last logged in users and system last reboot time and date, enter:
$ last reboot | less
Sample outputs:
Fig.01: last command in action
The last command searches back through the file /var/log/wtmp and displays a list of all users logged in (and out) since that file was created. The pseudo user reboot logs in each time the system is rebooted. Thus last reboot command will show a log of all reboots since the log file was created.
Finding systems last shutdown date and time
To display last shutdown date and time use the following command:
$ last -x|grep shutdown | head -1
Sample outputs:
- -x: Display the system shutdown entries and run level changes.
Here is another session from my last command:
$ last
$ last -x
$ last -x reboot
$ last -x shutdown
Sample outputs:
Fig.01: How to view last Linux System Reboot Date/Time
- 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 ➔
Find out Linux system up since…
Another option as suggested by readers in the comments section below is to run the following uptime command:
$ uptime -s
Sample outputs:
macOS (OS X)/Unix/FreeBSD find out last reboot and shutdown time command examples
Type the following last command:
$ last reboot
Sample outputs from OS X unix:
To see shutdown date and time, enter:
$ last shutdown
Sample outputs:
How do I find who rebooted/shutdown the Linux box?
You need to enable psacct service and run the following command to see info about executed commands including user name. Type the following lastcomm command along with the grep command/egrep command to see:
# lastcomm userNameHere
# lastcomm commandNameHere
# lastcomm | more
# lastcomm reboot
# lastcomm shutdown
## OR see both reboot and shutdown time
# lastcomm | egrep ‘reboot|shutdown’
Sample outputs:
So root user rebooted the box from ‘pts/0’ on Sun, Dec, 27th at 23:49 local time.
Conclusion
- For more information read last command man page and learn how to use the tuptime command on Linux server to see the historical and statistical uptime.
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.
On my FC5 system instead of
last reboot | head -1
I can type
last reboot -1
Please give a try by your own!! I think it will not work dude.
i couldn’t find out the error. please help me.
#Send list of users logged on to server via email
59 11 * * * last | grep date ‘+%a %b %d’ > /tmp/users.out ; mail -s “Users Logged Today†ephrondiana@gmail.com
when i tried to execute,
$ last |grep date ‘+%a %b %d’
i got no such file or directory error.
thanks a lot vivek.i din’t expect this much fast reply.But unfortunately when i execute,
$ last | grep $(date ‘+%a %b %d’)
i couldn’t get anything.Please help
My bad…I forgot to include double quote …
Also you may wanna try out:
Thanks vivek.its working great…..
the command “last reboot” worked for me, on my mac!
Can we find who rebooted the linux box?
In order to track who rebooted a linux machine, I would:
– disable root logins; many users sharing root is bad
– create a list of sudoers, so only people listed there could shutdown / reboot / halt
– /var/log/messages would contain traces of who ran sudo shutdown -r now or such
Thanks a lot!
I help me!
wtmp is rotated by the system, so the last solution will stop working. I believe the most reliable solution is:
The uptime idea from Sam is nice but really that just returns the uptime (same as the uptime command) in date format.
last | grep USERNAME | grep tty | head -n 1 |awk -F ‘ ‘ ‘
Is there any way to check if the system is currently rebooting? Or shutting down
–
I made a cron job that will reboot the server when a specific file exists (deleting that file too of course)
So that I can use php to make it and signal a reboot when needed
When cron job fires, the few seconds of shutting down will trigger database connection error
So I want to know if there is any standard way of knowing the system is rebooting aside from making another file that existence signals “server is rebooting” (which I don’t know how to delete when server is back up anyway)
Thank u 🙂 for info
tuptime is an other command that you can use for get this information. I found it after trying all the typical commands. I think that it covers better this subject that the solutions proposed here
An example, with enumerate option:
# tuptime -e
Startup: 1 at 08:25:03 AM 08/28/2015
Uptime: 14 minutes and 38 seconds
Shutdown: OK at 08:39:41 AM 08/28/2015
Downtime: 6 seconds
Startup: 2 at 08:39:48 AM 08/28/2015
Uptime: 10 minutes and 36 seconds
Shutdown: BAD at 08:50:24 AM 08/28/2015
Downtime: 7 minutes and 16 seconds
Startup: 3 at 08:57:41 AM 08/28/2015
Uptime: 10 minutes and 22 seconds
Shutdown: BAD at 09:08:03 AM 08/28/2015
Downtime: 6 minutes and 12 seconds
Startup: 4 at 09:14:16 AM 08/28/2015
Uptime: 1 minutes and 7 seconds
Shutdown: BAD at 09:15:23 AM 08/28/2015
Downtime: 2 minutes and 35 seconds
Startup: 5 at 09:17:59 AM 08/28/2015
Uptime: 1 minutes and 15 seconds
Shutdown: BAD at 09:19:14 AM 08/28/2015
Downtime: 8 hours, 32 minutes and 8 seconds
Startup: 6 at 05:51:23 PM 08/28/2015
Uptime: 2 days, 16 hours, 53 minutes and 19 seconds
Shutdown: BAD at 10:44:42 AM 08/31/2015
Downtime: 22 hours, 13 minutes and 17 seconds
Startup: 7 at 08:58:00 AM 09/01/2015
Uptime: 7 hours, 23 minutes and 51 seconds
Shutdown: OK at 04:21:51 PM 09/01/2015
Downtime: 11 seconds
Startup: 8 at 04:22:03 PM 09/01/2015
Uptime: 41 seconds
Shutdown: OK at 04:22:44 PM 09/01/2015
Downtime: 6 seconds
Startup: 9 at 04:22:51 PM 09/01/2015
Uptime: 4 minutes and 11 seconds
Shutdown: OK at 04:27:02 PM 09/01/2015
Downtime: 5 seconds
Startup: 10 at 04:27:08 PM 09/01/2015
Uptime: 1 days, 16 hours, 14 minutes and 32 seconds
System startups: 10 since 08:25:03 AM 08/28/2015
System shutdowns: 4 ok – 5 bad
Average uptime: 11 hours, 19 minutes and 27 seconds
Average downtime: 3 hours, 6 minutes and 12 seconds
Current uptime: 1 days, 16 hours, 14 minutes and 32 seconds since 04:27:08 PM 09/01/2015
Uptime rate: 78.49 %
Downtime rate: 21.51 %
System uptime: 4 days, 17 hours, 14 minutes and 35 seconds
System downtime: 1 days, 7 hours, 2 minutes and 1 seconds
System life: 6 days, 0 hours, 16 minutes and 37 seconds
Seriously? No one came up with a simple ‘uptime -s’ ?
Источник
Время последнего перезапуска системы Linux
Всем привет, в данном посту мы рассмотрим пару простых примеров того как можно просмотреть время последнего перезапуска системы Linux. Под перезапуском системы мы будем подразумевать её перезагрузку, либо её выключение с последующим включением. В общем, суть понятна, и теперь давайте предположим, как это может быть полезным в повседневной жизни. Вы администрируете сервер под Linux, в момент вашего отсутствия ваш сервер, по каким либо причинам был перезагружен, либо был выключен вовсе.
Первое что приходит в голову традиционно — смотреть логи системы, открываете логи, а там море записей с полезной и не очень информацией, как же найти нужную запись? Конечно, к каждой записи в логах есть время события, а это значит, зная время сбоя, будет гораздо проще найти записи в логах. И это лишь один из примеров того, как могут быть информация о времени последнего перезапуска системы.
После небольшого вступления давайте посмотрим, как же можно посмотреть время последнего перезапуска системы. Для этих целей можно воспользоваться командой «last». Команда выбирает информацию из файла /var/log/wtmp, и показывает на экран дату и время перезагрузок системы.
Показ даты и времени всех перезагрузок системы
Как видно чем дольше эксплуатируется машина, тем больше может быть список перезагрузок. Поэтому можно вывести только одну запись, саму последнюю.
Показ даты и времени последней перезагрузки системы
То что мы видим, это касается перезагрузки системы. Теперь просмотрим информацию, когда сервер завершал свою работу, для этого мы так же воспользуемся командой last.
Просмотр даты и времени завершения работы системы
Просмотр даты и времени последнего завершения работы системы
Аналогичная команда для просмотра последней перезагрузки системы
Хотелось бы отметить так же ещё и другую команду, которая показывает дату последней перезагрузки системы.
На этом всё, желаю вам меньше перебоев в работе сервера. Касательно темы, рекомендую к прочтению поста о командах для просмотра информации о системе Linux.
Источник