Programing

Bash 스크립트로 사용자 계정과 비밀번호를 자동으로 추가하는 방법은 무엇입니까?

lottogame 2020. 5. 17. 10:28
반응형

Bash 스크립트로 사용자 계정과 비밀번호를 자동으로 추가하는 방법은 무엇입니까?


Linux (Fedora 10)에서 사용자 계정을 만들고 bash 스크립트 (또는 필요한 경우)를 통해 자동으로 암호를 할당 할 수 있어야합니다.

Bash를 통해 사용자를 쉽게 만들 수 있습니다. 예 :

[whoever@server ]#  /usr/sbin/useradd newuser

Bash에서 암호를 기능적으로 유사하지만 자동으로 지정할 수 있습니까?

[whoever@server ]# passwd newuser
Changing password for user testpass.
New UNIX password:
Retype new UNIX password: 
passwd: all authentication tokens updated successfully.
[whoever@server ]#

passwd 명령을 실행하여 파이프 입력을 보낼 수 있습니다. 따라서 다음과 같이하십시오.

echo thePassword | passwd theUsername --stdin

chpasswd 를 사용할 수도 있습니다 .

echo username:new_password | chpasswd

그래서, 당신은 사용자의 암호를 변경 username하는 new_password.


나는 나 자신에게 같은 것을 요구하고 있었고, 파이썬 스크립트에 의존하고 싶지 않았다.

이것은 하나의 bash 행에 정의 된 비밀번호를 가진 사용자를 추가하는 행입니다.

useradd -p $(openssl passwd -1 $PASS) $USER

아래 코드는 우분투 14.04에서 작동했습니다. 다른 버전 / 리눅스 변형에서 사용하기 전에 사용해보십시오.

# quietly add a user without password
adduser --quiet --disabled-password --shell /bin/bash --home /home/newuser --gecos "User" newuser

# set password
echo "newuser:newpassword" | chpasswd

Tralemonkey의 접근 방식이 마음에 들었지만 echo thePassword | passwd theUsername --stdin서면으로는 제대로 작동하지 않았습니다. 그러나 이것은 나를 위해 일했습니다.

echo -e "$password\n$password\n" | sudo passwd $user

-e\n새 줄로 인식 하는 것입니다.

sudo 우분투에 대한 루트 액세스입니다.

큰 따옴표는 $변수 를 인식 하고 확장하는 것입니다.

위의 명령은 암호 및 새 줄, 두 번에 통과하는 passwd것입니다, passwd필요합니다.

변수를 사용하지 않으면 아마도 효과가 있다고 생각합니다.

echo -e 'password\npassword\n' | sudo passwd username

작은 따옴표로 충분합니다.


다음은 저에게 효과적이며 Ubuntu 14.04에서 테스트되었습니다. 사용자 입력이 필요없는 하나의 라이너입니다.

sudo useradd -p $(openssl passwd -1 $PASS) $USERNAME

@Tralemonkey에서 가져온


-p 옵션을 사용할 수 있습니다.

useradd -p encrypted_password newuser

불행히도,이 경우 암호를 직접 해시해야합니다 (passwd가 암호를 대신 사용함). 불행히도 일부 데이터를 해시하는 표준 유틸리티가없는 것 같으므로 직접 작성해야합니다.

다음은 암호화를 위해 작성한 작은 Python 스크립트입니다. pcrypt라고 가정하면 위의 명령 줄을 다음과 같이 작성하십시오.

useradd -p $(pcrypt ${passwd}) newuser

알아야 할 몇 가지 경고.

  1. pcrypt가 실행되는 동안 일반 텍스트는 ps 명령을 통해 모든 사용자에게 표시됩니다.
  2. pcrypt는 이전 스타일의 crypt 기능을 사용합니다. MD5 해시와 같이 더 현대적인 것을 사용하는 경우 pcrypt를 변경해야합니다.

그리고 여기 pcrypt가 있습니다 :

#!/usr/bin/env python

import crypt
import sys
import random

saltchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

def salt():
    return random.choice(saltchars) + random.choice(saltchars)

def hash(plain):
    return crypt.crypt(arg, salt())

if __name__ == "__main__":
    random.seed()
    for arg in sys.argv[1:]:
        sys.stdout.write("%s\n" % (hash(arg),))

홈 디렉토리 및 비밀번호로 sudo 사용자를 작성하는 단일 라이너.

useradd -m -p $(openssl passwd -1 ${PASSWORD}) -s /bin/bash -G sudo ${USERNAME}

--stdin데비안에서는 작동하지 않습니다. 그것은 말한다 :

`passwd: unrecognized option '--stdin'`

이것은 나를 위해 일했다 :

#useradd $USER
#echo "$USER:$SENHA" | chpasswd

여기에 다른 좋은 방법이 있습니다.


bash 스크립트에서 expect를 사용할 수 있습니다.

에서 http://www.seanodonnell.com/code/?id=21

#!/usr/bin/expect 
######################################### 
#$ file: htpasswd.sh 
#$ desc: Automated htpasswd shell script 
######################################### 
#$ 
#$ usage example: 
#$ 
#$ ./htpasswd.sh passwdpath username userpass 
#$ 
###################################### 

set htpasswdpath [lindex $argv 0] 
set username [lindex $argv 1] 
set userpass [lindex $argv 2] 

# spawn the htpasswd command process 
spawn htpasswd $htpasswdpath $username 

# Automate the 'New password' Procedure 
expect "New password:" 
send "$userpass\r" 

expect "Re-type new password:" 
send "$userpass\r"

나는 몇 년 후 내가 올 것이라는 것을 알고 있지만, 아무도 usermod를 제안하지 않았다.

usermod --password `perl -e "print crypt('password','sa');"` root

누군가 이전 HPUX에서이 작업을 수행하려는 경우 사용할 수 있습니다 usermod.sam.

/usr/sam/lbin/usermod.sam -F -p `perl -e "print crypt('password','sa');"` username

-F는 스크립트를 실행하는 사람이 현재 사용자 인 경우에만 필요합니다. 물론 해시를 만들기 위해 Perl을 사용할 필요는 없습니다. 그 대신 openssl 또는 다른 많은 명령을 사용할 수 있습니다.


여기 당신을 위해 그것을 할 스크립트가 있습니다 .....

원하는 경우 사용자 목록 (또는 한 명의 사용자)을 추가 할 수 있습니다. 한 번에 모두 암호가 다릅니다. 보너스로 스크립트 끝에 각 사용자 비밀번호 목록이 표시됩니다. .... 원하는 경우 사용자 유지 관리 옵션을 추가 할 수 있습니다

처럼:

chage -m 18 $user
chage -M 28 $user

to the script that will set the password age and so on.

=======

#!/bin/bash

# Checks if you have the right privileges
if [ "$USER" = "root" ]
then

# CHANGE THIS PARAMETERS FOR A PARTICULAR USE
PERS_HOME="/home/"
PERS_SH="/bin/bash"

   # Checks if there is an argument
   [ $# -eq 0 ] && { echo >&2 ERROR: You may enter as an argument a text file containing users, one per line. ; exit 1; }
   # checks if there a regular file
   [ -f "$1" ] || { echo >&2 ERROR: The input file does not exists. ; exit 1; }
   TMPIN=$(mktemp)
   # Remove blank lines and delete duplicates 
   sed '/^$/d' "$1"| sort -g | uniq > "$TMPIN"

   NOW=$(date +"%Y-%m-%d-%X")
   LOGFILE="AMU-log-$NOW.log"

   for user in $(more "$TMPIN"); do
      # Checks if the user already exists.
      cut -d: -f1 /etc/passwd | grep "$user" > /dev/null
      OUT=$?
      if [ $OUT -eq 0 ];then
         echo >&2 "ERROR: User account: \"$user\" already exists."
         echo >&2 "ERROR: User account: \"$user\" already exists." >> "$LOGFILE"
      else
         # Create a new user
         /usr/sbin/useradd -d "$PERS_HOME""$user" -s "$PERS_SH" -m "$user"
         # passwdgen must be installed
         pass=$(passwdgen -paq --length 8)
         echo $pass | passwd --stdin $user
         # save user and password in a file
         echo -e $user"\t"$pass >> "$LOGFILE"
         echo "The user \"$user\" has been created and has the password: $pass"
      fi
   done
   rm -f "$TMPIN"
   exit 0
else
   echo >&2 "ERROR: You must be a root user to execute this script."
   exit 1
fi

===========

Hope this helps.

Cheers, Carel


From IBM (https://www.ibm.com/support/knowledgecenter/ssw_aix_61/com.ibm.aix.cmds1/chpasswd.htm):

Create a text file, say text.txt and populate it with user:password pairs as follows:

user1:password1
user2:password2
...
usern:passwordn

Save the text.txt file, and run

cat text.txt | chpassword

That's it. The solution is (a) scalable and (b) does not involve printing passwords on the command line.


I've tested in my own shell script.

  • $new_username means newly created user
  • $new_password means newly password

For CentOS

echo "$new_password" | passwd --stdin "$new_username"

For Debian/Ubuntu

echo "$new_username:$new_password" | chpasswd

For OpenSUSE

echo -e "$new_password\n$new_password" | passwd "$new_username"

Tralemonkey's solution almost worked for me as well ... but not quite. I ended up doing it this way:

echo -n '$#@password@#$' | passwd myusername --stdin

2 key details his solution didn't include, the -n keeps echo from adding a \n to the password that is getting encrypted, and the single quotes protect the contents from being interpreted by the shell (bash) in my case.

BTW I ran this command as root on a CentOS 5.6 system in case anyone is wondering.


The solution that works on both Debian and Red Hat. Depends on perl, uses sha-512 hashes:

cat userpassadd
    #!/usr/bin/env bash

    salt=$(cat /dev/urandom | tr -dc A-Za-z0-9/_- | head -c16)
    useradd -p $(perl -e "print crypt('$2', '\$6\$' . '$salt' . '\$')") $1

Usage:

userpassadd jim jimslongpassword

It can effectively be used as a one-liner, but you'll have to specify the password, salt and username at the right places yourself:

useradd -p $(perl -e "print crypt('pass', '\$6\$salt\$')") username

{ echo $password; echo $password; } | passwd $username 

For RedHat / CentOS here's the code that creates a user, adds the passwords and makes the user a sudoer:

#!/bin/sh
echo -n "Enter username: "
read uname

echo -n "Enter password: "
read -s passwd

adduser "$uname"
echo $uname:$passwd | sudo chpasswd

gpasswd wheel -a $uname

usage: ./my_add_user.sh USER PASSWD

code:

#!/bin/bash
# my_add_user.sh

if [ "$#" -lt 2 ] 
 then
       echo "$0 username passwd"
       exit
fi

user=$1
passwd=$2

useradd $user -d /data/home/$user  -m  ;
echo $passwd | passwd $user --stdin;

참고URL : https://stackoverflow.com/questions/2150882/how-to-automatically-add-user-account-and-password-with-a-bash-script

반응형