Linux generate random string

How to Generate Random String in Bash

In this tutorial, we shall look at various ways we can generate random strings in bash. This functionality can be useful when creating usernames, passwords, or seed data.

Method 1: md5 Hash

The very first method we can use to generate a random string in bash is md5 checksums. Bash has the $RANDOM variable, which produces a random number. We can pipe this value to md5sum to get a random string.

The $RANDOM variable is always random. As a result, the md5 checksum produces is always random.

Method 2: UUID

You can also use the kernel UUID generator in /proc/sys/kernel/random/uuid. This will give you will get a unique hexadecimal value that you can convert to a random string using the sed and head command:

Method 3: Pseudo devices

You have heard the phrase, “Everything in Linux is a file.” One of the concepts that make this statement true is the ability to express devices as files.

Files located in /dev are known as pseudo devices; they act as bridges between the kernel and the hardware. One of the files in this directory is the uradom file.

The urandom file provides an interface to access the kernel random number generator. Hence, we can use it to generate a random string as illustrated below:

We pipe the output of urandom to tr, which generates alphanumeric values and then folds the values to the width of up to 20 characters. Finally, we get one lined string with head -n.

To get multiple values at once, change the value of head -n to the number of lines required.

Method 4: Base64

You can also use the base64 utility to generate a random string. For example, using the $RANDOM variable, we can do:

Method 5: OpenSSL Pseudo Random Bytes

OpenSSL rand command allows you to generate random bytes based on the type specified. These types include base63 and hex values.

Or use base64 as:

Conclusion

In closing, bash provides various utilities you can use to generate random strings. Therefore, all you need to do is combine various tools and develop a clever way to get random strings that suit your needs.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list

Источник

Как сгенерировать случайную строку?

Я хотел бы создать случайную строку (например, пароли, имена пользователей и т. Д.). Должна быть возможность указать необходимую длину (например, 13 символов).

Какие инструменты я могу использовать?

(Из соображений безопасности и конфиденциальности желательно, чтобы строки генерировались в автономном режиме, а не в Интернете на веб-сайте.)

Мой любимый способ сделать это, используя /dev/urandom вместе с, tr чтобы удалить нежелательных символов. Например, чтобы получить только цифры и буквы:

Если у вас есть проблемы с tr жалобами на ввод, попробуйте добавить LC_ALL=C вот так:

Для генерации случайного пароля вы можете использовать pwgen :

pwgen генерирует случайные, бессмысленные, но произносимые пароли. Эти пароли содержат либо только строчные буквы, либо смешанные прописные и строчные буквы, либо вставленные цифры. Заглавные буквы и цифры размещаются таким образом, чтобы их было легче запомнить, когда запоминаются только слова.

Сгенерируйте 7 паролей длиной 13:

Как упоминалось в комментариях, вы можете избежать уменьшения энтропии с помощью -s аргумента (то есть генерировать более безопасные, совершенно случайные, но трудно запоминающиеся пароли):

Читайте также:  What is virtual desktop in linux

Для генерации случайных имен пользователей вы можете использовать gpw :

Этот пакет генерирует произносимые пароли. Он использует статистику трехбуквенных комбинаций (триграфов), взятых из любых словарей, которые вы используете.

Генерация 7 паролей (имен пользователей) длиной 13:

Я использую openssl команду, швейцарский армейский нож криптографии.

Вот как я это делаю. Он генерирует 10 символов случайной строки. Вы можете оптимизировать его, заменив «свернуть» другими инструментами для обработки строк.

Чтобы создать пароль с максимально возможной энтропией с помощью стандартных инструментов Linux, которые встроены в каждый дистрибутив, который я использую:

Это выводит все печатные символы ASCII — от 32 (пробел) до 126 (тильда,

). Длина пароля может управляться с head русским -c флагом. Есть также другие возможные наборы символов tr (чтобы не включать пробел, используйте только символы 33-126 [:graph:] ).

В зависимости от уровня случайности, который вы хотите, вы можете просто использовать встроенную переменную bash (также zsh и ksh , возможно, других) $RANDOM :

Методы, читающие непосредственно из /dev/urandom , намного проще, но для завершения вы также можете использовать $RANDOM :

Важно : это решение будет генерировать только случайные строки, используя первые 10 букв алфавита. Будет ли этого достаточно для вас, зависит от того, для чего вам это нужно.

Вдохновленный Пабло Репетто, я получил это легко запоминающееся решение:

-z избегает многострочного вывода

-e повторяем результат

-r разрешить любому персонажу появляться несколько раз

-n20 случайная строка длиной 20 символов

<0..9>разрешенные классы символов

shuf является частью linux coreutils и широко доступна или, по крайней мере, портирована.

@Brandin объяснил в комментарии к другому ответу, как получить максимум 100 байтов от /dev/urandom использования head -c 100 . Еще один способ сделать это с dd :

В 2>/dev/null конце dd команды подавляется вывод «. records in / . records out».

Я не знаю каких-либо существенных преимуществ / недостатков между этими двумя методами.

У меня была проблема с обоими методами tr жаловаться на ввод. Я думал, что это потому, что ему не нравилось получать бинарный ввод, и поэтому предложил сначала выполнить фильтрацию /dev/random с помощью iconv -c -t US . Однако Жиль предложил другой диагноз и решение, которое работает для меня:

APG включен по умолчанию в некоторых дистрибутивах Linux.

Чтобы сгенерировать пароли размером от 5 до 10 в подмножествах Special, Numeric, Capital и Lower, введите команду:

Как сказал @landroni в комментарии.

Вы можете использовать один из md5 инструментов, который имеет именно эту цель. В случае создания совершенно случайного пароля вы можете использовать md5pass . Это очень простой в использовании и очень полезный инструмент, поскольку вы можете использовать «обычный текст» вместе с «солью» для создания скачкообразного кода того же пароля, который вы можете восстановить впоследствии, или, в качестве альтернативы, вы можете получить полностью случайный пароль все время. Общее использование:

где password — выбранное слово, которое будет использоваться для построения случайной строки, и salt переход в байтах, который будет использоваться. Нравится:

Это создаст для вас пароль с произвольной последовательностью. Если вы используете нет salt , то вы не сможете воссоздать эту же строку позже.

Однако, если вы используете salt как это:

затем вы можете создать последовательность, которую вы можете восстановить, если вы используете слово в сочетании с той же солью (или прыжком), если оно было первоначально определено.

Источник

10 способов генерации случайного пароля в командной строке

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

Мы позаимствовали эти команды на сайте Command-Line Fu и протестировали их на своём Linux-компьютере, чтобы убедиться, что все они работают. Вы можете использовать по крайней мере некоторые из них и в Windows с установленным Cygwin , хотя мы и не тестировали их в этой конфигурации. Но последний вариант наверняка будет работать.

Генерация случайного пароля

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

Читайте также:  Для чего нужен windows блокнот

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. А какой способ используете вы?

Источник

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.

Читайте также:  Mac os чем писать диски

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

Источник

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