- 10 способов генерации случайного пароля в командной строке
- Генерация случайного пароля
- HowTo: Linux Random Password Generator Command
- Bash function to create random password
- MNorin.com
- Блог про Linux, Bash и другие информационные технологии
- Генератор паролей на bash
- Используемые символы
- Длина пароля
- Скрипт-генератор паролей на bash
- Похожие посты:
- Генератор паролей на bash : 12 комментариев
- 8 Ways to Generate a Random Password on Linux Shell
- Generation of a password with OpenSSL
- Generation of a password using urandom
- Generation of a password using pwgen
- Generation of a password using gpg
- Generation of a password using SHA
- Generation of a password via an easy way
- Generation of a password using apg
- Generation of a password using makepasswd
- Conclusion
- Karim Buzdar
10 способов генерации случайного пароля в командной строке
Одна из очень привлекательных особеностей Linux состоит в том, что вы можете одну и ту же задачу решить сотней различных способов. Даже если речь идет о таком простом деле, как генерация случайного пароля, существует множество команд, которые решают эту задачу в командной строке. В настоящей заметке приведены 10 вариантов того, как это можно сделать.
Мы позаимствовали эти команды на сайте Command-Line Fu и протестировали их на своём Linux-компьютере, чтобы убедиться, что все они работают. Вы можете использовать по крайней мере некоторые из них и в Windows с установленным Cygwin , хотя мы и не тестировали их в этой конфигурации. Но последний вариант наверняка будет работать.
Генерация случайного пароля
Каждую из приведенных ниже команд вы можете либо модифицировать, чтобы получить пароль желаемой длины, либо можете просто использовать первые х символов вывода, если не хотите использовать очень длинный пароль. Полагаю, что вы в любом случае используете менеджер паролей наподобие LastPass , так что нет нужды зпоминать пароли.
1. В этом методе используется SHA для того, чтобы получить из текущей даты хеш-функцию, которая фильтруется с помощью base64 и затем отображаются первые 32 символа.
2. Этот метод использует встроенную функцию /dev/urandom, вывод которой фильтруется, чтобы оставить только символы, допустимые в паролях. Затем в выоде оставляются только первые 32 символа.
3. В этом случае используется случайная функция из openssl, если этот пакет установлен в вашей системе.
4. Этот вариант подобен предыдущему с urandom, но команды используются в обратном порядке. Bash — очень мощная вещь!
5. Еще один пример, в котором для фильтрации используется команда strings , которая предназначена для вывода пригодных для печати строк файла, но в этом случае обрабатывает вывод urandom .
6. А вот еще более простой вариант использования urandom .
7. В этом варианте используется очень полезная команда dd .
8. Вы можете даже создать случайный пароль, который можно набирать одной только левой рукой.
9. Если создавать пароли вам приходится часто, будет неплохой идеей написать для этого функцию. После этого вы сможете использовать randpw в любое время, как только вам потребуется создать новый пароль. Лучше всего поместить ее в ваш файл
Тот же самый прием вы можете использовать с любым из приведенных выше примеров, достаточно заменить содержимое фигурных скобок < >.
10. И, наконец, самый простой способ сгенерить пароль в командной строке. Этот способ работает в Linux, Windows с Cygwin и,вероятно, в Mac OS X. Я уверен, что некоторые люди скажут, что этот способ дает не такой случайный результат, как некоторые из предыдущих вариантов, но, честное слово, он вполне удовлетворительно работает.
Да, и этот вариант достаточно легко запоминается.
Есть и другие способы генерации случайного пароля в командной строке Linux, например, команда mkpasswd , которая предназначена для задания пароля к пользовательскому экаунту в Linux. А какой способ используете вы?
Источник
HowTo: Linux Random Password Generator Command
- /dev/urandom file – Linux kernel’s random number generator source/interface. A read from the /dev/urandom device will not block waiting for more entropy.
- tr command – Translate or delete characters. Used to remove unwanted characters from /dev/urandom.
- head command – Output the first part of files.
- xargs command – build and execute command lines from standard input/pipe.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | Bash |
Est. reading time | 2m |
Bash function to create random password
/.bashrc file, enter:
$ vi $HOME/.bashrc
Append the following code:
- 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 ➔
Save and close the file. Source
/.bashrc again, enter:
$ source
To generate random password, enter:
$ genpasswd
Sample outputs:
To generate 8 character long random password, enter:
$ genpasswd 8
Sample outputs:
Linux Random Password Generator Command
- See how to use makepasswd> command to generate true random passwords by using the /dev/random feature of Linux.
- Man pages: urandom(4)
🐧 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.
Cool tip, the following command always worked for me:
openssl rand -base64 6
Thanks for the Tips, and cool blog too.
keep up the good work.
Debian / Ubuntu: sudo apt-get install pwgen
Centos / Redhat : yum –enablerepo=rpmforge install bind-utils secpwgen
Thanks for the tips…its work. ^_^
Well, the need for random password generation is an important topic, and your example of User-Defined Function is nice to know, but there is already a nice command for it! ;-D
It’s named [mkpasswd]
To get manual page, type in : man mkpasswd
MKPASSWD(1)
NAME
mkpasswd – Overfeatured front end to crypt(3)
SYNOPSIS
mkpasswd PASSWORD SALT
DESCRIPTION
mkpasswd encrypts the given password with the crypt(3) libc function using the given salt.
OPTIONS
-S, –salt=STRING
Use the STRING as salt. It must not contain prefixes such as $1$.
-R, –rounds=NUMBER
Use NUMBER rounds. This argument is ignored if the method choosen does not support variable rounds. For the
OpenBSD Blowfish method this is the logarithm of the number of rounds.
-m, –method=TYPE
Compute the password using the TYPE method. If TYPE is help then the available methods are printed.
-P, –password-fd=NUM
Read the password from file descriptor NUM instead of using getpass(3). If the file descriptor is not connected
to a tty then no other message than the hashed password is printed on stdout.
-s, –stdin
Like –password-fd=0.
For ubuntu i like to use apg
apt-get install apg
Then just run:
apg
The original example is very unsafe since all local users can see your password via the process list.
On Mac OS I have to add LC_TYPE in front of tr line e.g.
LC_CTYPE=C tr -dc A-Za-z0-9_ David Oct 25, 2014 @ 4:48
Thanks, Sebastian! I was getting that error, too.
on mac this one not work for me
LC_CTYPE=C tr -dc A-Za-z0-9_
but if we change with LC_ALL can work
LC_ALL=C tr -dc A-Za-z0-9_
is xargs really necessary here?
also, for passwords no special chars is quick to hack, so I like to use ASCII chars 50 -172 (right after the quotes so that it doesn’t interfere with variable assignment.
Источник
MNorin.com
Блог про Linux, Bash и другие информационные технологии
Генератор паролей на bash
Время от времени приходится менять пароли. Все знают, что хороший пароль должен включать большие и малые латинские буквы, цифры и специальные символы. При этом они не должны быть слишком короткими. И каждый раз придумывать их все труднее и труднее, особенно если использовать разные пароли на разных сервисах. Можно для этого использовать, например, программу pwgen или генератор, встроенный в keepassx. А можно написать простой генератор паролей на bash.
Используемые символы
Будем использовать следующие символы: Большие и малые буквы латинского алфавита (A-Z и a-z), цифры (0-9) и символы «!@#$%^&*()?/\[]<>-+_=<>.,». Такое сочетание обеспечит максимальную надежность.
Длина пароля
Длина пароля будет 16 символов. Если вам нужен более короткий пароль, то вы можете указать меньшую длину в скрипте, либо добавить опцию командной строки.
Скрипт-генератор паролей на bash
Самое первое, что нам необходимо — это переменная, содержащая все символы, которые мы будем использовать. Также нужна будет переменная, содержащая длину пароля и переменная для хранения самого пароля.
Вот и всё. Это весь скрипт. И с его помощью мы можем получить пароль, который удовлетворяет всем распространенным требованиям безопасности. Осталась только одна проблема — запомнить его.
Похожие посты:
Генератор паролей на bash : 12 комментариев
Практический смысл в таком скрите весьма минимален. Это как в притче о чуваке, который всю жизнь учился ходить по воде, хотя можно просто использовать мост. Есть огромная куча сайтов для генерации паролей. А есть даже те, которые со своим API http://www.passwordrandom.com/Meter.aspx
Хотя, с точки зрения тренировки и практики — свой велосипед в пароледеланьи — вполне неплохая метода к профессиональному росту 🙂
Этот скрипт тут как раз с точки зрения тренировки. А вот сайтам для генерации паролей я бы не доверял, пожалуй. 🙂
Большое спасибо! Ваш скрипт пригодился. bash для автоматизации задач, одна из них — периодическая смена паролей.
Спасибо, пригодился для создания разово 200 юзеров
Это хорошо, но где спецсимволы?
Максим привет! А как прикрутить к твоему генератору НЕ повторяющиеся Uppercase Letters и Lowercase Letters, а также пробелы в пароле?
Зы: Навеяно мотивами — http://www.passwordmeter.com/
К, примеру вот такой 26-ти значный пароль удоволетворяет требованиям сайта:
k Eu&V+Gz) $PiC@LqF-w%tYa2
Привет. Пробел просто добавить в список символов SYMBOLS, а на уникальность проверять можно, например, так:
if [[ passw = *$
А чего комменты не публикуются на сайте?
А как сгенерировать пароль случайным образом, но чтобы в нём всегда обязательно был минимум один спец-символ, цифра и буквы в разных регистрах? А то временами генерируется только буквенный пароль.
Я использую следующий код для генерации MySql пароля, но время от времени он не соответствует уровню MEDIUM (Your password does not satisfy the current policy requirements):
Можно попробовать так (если количество кода не смущает):
Источник
8 Ways to Generate a Random Password on Linux Shell
Having a strong password when authenticating to a service by username and password is very important. Sometimes, you need to protect your account or server, and try to keep your data safe and secure. It is often said that a strong password must have a minimum of 14 characters with variations like you may have lowercases/uppercases in the characters and alphabets. Mostly the long password is considered to be much more secure than a short one since it is hard to get. In this tutorial, we will see many ways to generate a strong password from Linux command line. We will have a look at many different means to create a stronger password that is secure enough, using the Linux command line. You need to generate a stronger password from the command line so, it has various different methods and utilities that are already available. We will be discussing many of the methods and you may choose any of the ways for generation of a password as per your need.
Generation of a password with OpenSSL
Several methods, exist in Linux to create and generate the passwords for Linux command line. The first one we are trying is by using OpenSSL. Following are the steps that need to be followed for this purpose.
Step 1: First of all, open Terminal by clicking on Ubuntu launcher and search for Terminal.
Step 2: Now click on the Terminal and wait for the terminal to open.
Step 3: Once the terminal is opened, you will have a screen like this:
Step 4:
The command that is used to generate a stronger password includes OpenSSL rand function. This will help us generate 14 random characters in a string. The command is “openssl rand –base64 14”.
Advertisement
The outcome will be a strong password of 14 characters as shown below.
Generation of a password using urandom
The second command which we are using to generate a password has filtered /dev/urandom output with tr. This will allow us to delete all of the unwanted characters and then help us to print the first 14 characters only.
The output of the above command is as follows:
The output has allowed us to print first 14 characters only by deleting all of the unwanted ones.
Generation of a password using pwgen
For using pwgen we need to install this tool at first. This tool will help us generate some random yet meaningless passwords. Although the passwords generated by it are random still are pronounceable. So, we will now install the tool using the following command.
Enter the credentials as asked
The installation will eventually begin. The command line will look just like the screen below.
Once the installation has been done, we will generate a random string having 14 characters in it.
The string we got randomly is this one.
Generation of a password using gpg
Gpg can also be used to generate a strong password of 14 characters. The gpg tool uses the following command to generate the 14 characters.
The outcome of this command is
And in the end, we have a password generated which is.
Generation of a password using SHA
We will use SHA in this method, we can also hash the date. It runs through the base64. As a result, we get an output as the top of the 32 characters.
Here is the outcome containing the 32 characters yet a strong password to keep the system safe.
Generation of a password via an easy way
The generation of a password is quite easy using the command line. Although it is not random still it is useful if we utilize the whole password. The easiest command for this purpose is as follows:
The outcome of the above command is a string as shown below.
And this command is very easy, and simple enough to remember.
Generation of a password using apg
APG is Automatic Password Generator, it is already installed on all Ubuntu systems. It is also an easily used utility. It helps us generate various passwords that are the random input.
In order to generate entire random passwords, we can run apg -a 1, which will give us the passwords with 8-10 random characters. The command we used for this purpose is apg –a 1. We will run and see various passwords generated in the output.
The output has many random passwords.
Generation of a password using makepasswd
“makepasswd” can also be used to generate passwords. For using this utility, we install it at first. We will use the command sudo apt-get install makepasswd.
Enter the required credentials.
On writing the credentials, the installation will begin.
Press Y to continue
Once the utility has been installed, we will write the command which is makepasswd –count NumberOfPasswords –minchars MinLengthOfPassword.
At first, we tell how many passwords we are aiming to generate and what must be the length of each of the password. Here we have asked to generate 4 passwords with length as eight for each of it.
The outcome is shown below. We have a total of 4 passwords with 8 characters in each of them.
The command is responsible for generating a list of random passwords based on the number of passwords we want to generate and the length is also defined by us.
Conclusion
In this tutorial, we have discussed many of the ways to generate the passwords from the command line of Linux. There are many methods that already exist. Few of the utilities are already present in Linux command line, while for those which are not are easily installable using the available commands. In the tutorial, we have discussed the utility openssh, urandom, pwegn, gpg, sha, date, apg, and makepasswd. All of these commands guarantee the generation of a stronger password from Linux command line and are useful for the user to maintain the security of their systems.
Karim Buzdar
About the Author: Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. You can reach Karim on LinkedIn
Источник