Linux смена пароля пользователя скриптом

Меняем пароль пользователю из bash скрипта (или просто командой из шелла).

Сейчас на КИТе нашли отличный способ сменить пароль пользователю из шелла (а значит и из скрипта). В общем, кто сталкивался с этой проблемой — поймут меня.

UPD: в комментариях указали другой способ смены пароля от рута:
root@host:~# echo «username:password» | chpasswd

Такой способ тоже подходит, но не является универсальным. Например, во FreeBSD утилиты chpasswd нет.
EOUPD

Сменим пароль руту на megapassword (запуск от рута):
root@host:~# echo -e «megapassword\nmegapassword\n» | passwd
Сменим пароль пользователю username (запуск от рута)
root@host:~# echo -e «megapassword\nmegapassword\n» | passwd username
Для того, что бы было понятнее, покажу что в кавычках с пробелами:
«megassword \n megapassword \n», где megapassword — новый пароль, а \n — «нажатие» клавиши enter (а точнее — перенос строки)

Сменим пароль пользователю username при запуске от username:
username:~$ echo -e «oldpassword\nmegapassword\nmegapassword\n» | passwd
Здесь добавляется третья строка в выводе echo, в которой нужно указать старый пароль. Чего я в общем-то вам не советую.

Ну и чтобы не было вопросов о том, что происходит:

inky@laptop1:~$ echo -e «oldpassword\nmegapassword\nmegapassword\n»
oldpassword
megapassword
megapassword

То есть мы на STDIN passwd скармливаем STDOUT echo. А echo и «жмет enter»

Источник

Смена пароля пользователя скриптом

В Linux несколько десятков пользователей (добавлены через useradd). Необходимо массово сменять пароли. Как это сделать? Пример на python подойдет лучше всего.

Re: Смена пароля пользователя скриптом

Re: Смена пароля пользователя скриптом

В многопользовательской системе такой подход не Ъ, так как обычно пользователи могу «видеть» чужые процессы, следовательно команда ps может «засветить» чужой пароль. Уж лучше создать файл и скормить его chpasswd: «chpasswd < filename", а файл потом удалить.

Re: Смена пароля пользователя скриптом

> так как обычно пользователи могут «видеть» чужые процессы

Это смотря какая система.У меня вот патчик есть от grsecurity..

Re: Смена пароля пользователя скриптом

> Необходимо массово сменять пароли. Вопрос поставлен неточно. Пароли Вы как-то задаёте, или надо автоматически сгенерить? > Как это сделать? while read LUSER PASSWD; do SALT="`pwgen -n -N 1 8`" CRYPTED=$(echo $PASSWD | mkpasswd -H md5 -S "$SALT" -s) usermod -p "$CRYPTED" $LUSER done > Пример на python подойдет лучше всего. Извините, питонам не обучен.

Re: Смена пароля пользователя скриптом

MD5HASH=$(python -c "import crypt; print crypt.crypt(. )")

Источник

Using the passwd Command from Within a Shell Script

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

Читайте также:  Сочетание клавиш смены языка линукс

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

1. Overview

Creating new users to give access to the system is a routine task for Linux system administrators. The task may involve multiple commands, like the useradd and passwd commands, as well as other administrative commands that may be required for specific Linux installations. Most system administrators usually create a shell script to simplify the task.

In this tutorial, we will quickly show the challenge of using the passwd command inside a shell script. We’ll then look at three methods to solve the problem.

2. Preparing a Simple User Creation Script

Let’s begin by exploring a straightforward script for creating a user. Firstly, the script takes the username to create as the first parameter. Inside, it calls useradd and passwd commands:

#!/bin/sh set -e NEWUSR=$1 useradd -m -U $NEWUSR passwd $NEWUSR 

Next, let’s set the executable flag and test it out, assuming we have sudo access:

$ chmod +x newuser.sh $ sudo ./newuser.sh testnewuser Changing password for user testnewuser. New password: 

Finally, we’ll just enter a specific password twice when prompted. If everything is fine, we’ll get the success message:

passwd: all authentication tokens updated successfully.

3. Making the Script Non-interactive

What if we want to automate the creation of new users using other tools such as Jenkins? Then, we would need to make the script non-interactive. That is to say that we do not want to provide the passwords of the new users via the command prompt. Instead, we want to pass the password values directly to the passwd command.

There are many ways to generate a password. Here, let’s use a simple set of commands that gives us the first 8 characters of the MD5 sum of the current Unix timestamp to use as the password:

$ date | md5sum | cut -c1-8 720e6264 

Next, we’ll use the piping technique to pass that value to the passwd command within the script:

#!/bin/sh set -e NEWUSR=$1 useradd -m -U $NEWUSR PASSWD=$(date | md5sum | cut -c1-8) echo $PASSWD | passwd $NEWUSR
$ sudo ./newuser.sh testnewuser2 Changing password for user testnewuser2. New password: Retype new password: Password change aborted. New password: Password change aborted. New password: Password change aborted. passwd: Have exhausted maximum number of retries for service 

The script call failed. The pipe successfully passed the password to the passwd command, but it failed to handle the second prompt with the “Retype new password” instruction.

Next, let’s explore a few methods to solve this problem.

3.1. Using stdin Option

The first method to pipe the new password to the passwd command is by using the stdin option. First, we need to check if the passwd command of our Linux distro supports that option:

$ passwd --help | grep stdin --stdin read new tokens from stdin (root only)

Next, we’ll insert it into the script:

#!/bin/sh set -e NEWUSR=$1 useradd -m -U $NEWUSR PASSWD=$(date | md5sum | cut -c1-8) echo $PASSWD | passwd --stdin $NEWUSR
$ sudo ./newuser.sh testnewuser3 Changing password for user testnewuser3. passwd: all authentication tokens updated successfully. 

3.2. Using chpasswd

The second method we explore here is to pipe the new password to the chpasswd command instead. While passwd expects the default mode of input via the input prompts, chpasswd expects the password to be passed via STDIN by default.

Читайте также:  Сколько всего дистрибутивов linux

Inside the script, we need to pipe both the username and the password separated by a “:” to the chpasswd command:

#!/bin/sh set -e NEWUSR=$1 useradd -m -U $NEWUSR PASSWD=$(date | md5sum | cut -c1-8) echo "$NEWUSR:$PASSWD" | chpasswd

Finally, let’s have a go at it:

$ sudo ./newuser.sh testnewuser4

Interestingly, chpasswd outputs no message when it is a success as it was designed to be used non-interactively.

3.3. Passing the Password Twice

This last method is considered hackish. Therefore, we should only choose this method if neither of the previous methods is available on our Linux installation.

This method involves crafting a string that contains the password twice using “\n” as the delimiter. For example, if the variable $PASSWD holds the value of the password, we craft a string that holds the value “$PASSWD\n$PASSWD“.

Just like the previous two methods, we pipe this string to the plain passwd command using the echo command:

#!/bin/sh set -e NEWUSR=$1 useradd -m -U $NEWUSR PASSWD=$(date | md5sum | cut -c1-8) echo -e "$PASSWD\n$PASSWD" | passwd $NEWUSR 

However, this time we add the -e option to the echo command to make the shell interpret the backslash-escaped “\n” character.

Testing the script shows two prompts that ask for the password twice, just like when we use the passwd command interactively. However, the prompts do not wait for inputs from us anymore:

$ sudo ./newuser.sh testnewuser5 Changing password for user testnewuser5. New password: Retype new password: passwd: all authentication tokens updated successfully. 

4. Conclusion

In this article, we’ve explored three methods to set a user’s password non-interactively inside a shell script. Two of those three methods use the passwd command, while the other uses an alternative chpasswd command.

Источник

How to change *your* Linux password via a Bash script

It’s easy enough to change another user’s password via a Bash script — just do echo newpw | sudo passwd username and bam, you’re done. But if you run echo newpw | passwd username it doesn’t work because it prompts you for your current password before letting you enter in your new password. How to change your password via Bash?

Only root can use passwd username for a different user. When you run passwd (without username ) as root it does not ask for the old password (on my Ubuntu 19.10 system).

Читайте также:  Все скины на линукс

Well, give it the current password then, < sleep .1; echo OLDPASSWORD; for i in 1 2; do sleep .1; echo Trump2020! ; done; >| passwd . Use . | script -c passwd /dev/null if passwd wants to read from a tty. But you really shouldn’t be doing that. Better say what you’re trying to achieve.

3 Answers 3

For all us newbies, can you help me understand the need for

@topher217 This is a here-string to provide input to a file descriptor (similar to a here-document ) by default to STDIN or fd0. See here

Thanks @JRFerguson. I also found these examples helpful. I’m not sure if I am wording this correctly, but now I understand that running chpasswd opens a kind of interactive STDIN terminal as opposed to expecting some string positional argument. You’re idea of using a here-string makes the usage of chpasswd resemble the syntax of a single line positional argument. I also found reading the man page for cat and comparing the examples of using it with and without a file positional arg helpful.

If you want to change the passwd of the current user, this should do as well:

echo -e "MyOldPasswd\nMyNewPasswd\nMyNewPasswd" | passwd 

That won’t work with any halfway reasonable setup. Only root can change other user’s passwords, via passwd user (it should prompt for the new password). To change your own password, do passwd , it should ask for the current password an then ask for the new one (and confirmation).

Allowing any random user to change other’s passwords is a huge security problem.

Why «That won’t work with any halfway reasonable setup» and «Allowing any random user to change other’s passwords»? This answer is unrelated to the current question. The current question is about changing your password. That works. That is secure.

@ValerioBozz I’d disagree. If the premise is wrong then any expectation about an answer will also be wrong

@roaima Maybe we are on different premises. The user already said «I was doing sudo». So anwering «Only root can change» is not useful to the user. It seems the user is not interested in avoiding root. We don’t need to say why root is necessary.

@ValerioBozz the OP seems confused about sudo . They demonstrate that they can use sudo to forcibly change any password without entering the old one, and then ask why (without sudo ) they have to enter their current password before being able to change it. Secondly, I think there may be an English language confusion. Someone can use «your» to mean any of «your» (of you, to whom I’m speaking) or «someone» (possibly including «me» and «you», but also anyone else). I think the last sentence is intended to mean «How can I change my password without needing to know the previous one?»

Источник

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