Using the passwd command from within a shell script

前端 未结 13 943
遥遥无期
遥遥无期 2020-11-28 04:20

I\'m writing a shell script to automatically add a new user and update their password. I don\'t know how to get passwd to read from the shell script instead of interactively

相关标签:
13条回答
  • 2020-11-28 04:33

    Here-document works if your passwd doesn't support --stdin and you don't want to (or can't) use chpasswd for some reason.

    Example:

    #!/usr/bin/env bash
    
    username="user"
    password="pass"
    
    passwd ${username} << EOD
    ${password}
    ${password}
    EOD
    

    Tested under Arch Linux. This passwd is an element of shadow-utils and installed from the core/filesystem package, which you usually have by default since the package is required by core/base.

    0 讨论(0)
  • 2020-11-28 04:37

    Sometimes it is useful to set a password which nobody knows. This seems to work:

    tr -dc A-Za-z0-9 < /dev/urandom | head -c44 | passwd --stdin $user
    
    0 讨论(0)
  • 2020-11-28 04:40

    Nowadays, you can use this command:

    echo "user:pass" | chpasswd
    
    0 讨论(0)
  • 2020-11-28 04:44

    The only solution works on Ubuntu 12.04:

    echo -e "new_password\nnew_password" | (passwd user)
    

    But the second option only works when I change from:

    echo "password:name" | chpasswd
    

    To:

    echo "user:password" | chpasswd
    

    See explanations in original post: Changing password via a script

    0 讨论(0)
  • 2020-11-28 04:47

    Tested this on a CentOS VMWare image that I keep around for this sort of thing. Note that you probably want to avoid putting passwords as command-line arguments, because anybody on the entire machine can read them out of 'ps -ef'.

    That said, this will work:

    user="$1"
    password="$2"
    adduser $user
    echo $password | passwd --stdin $user
    
    0 讨论(0)
  • 2020-11-28 04:47

    I stumbled upon the same problem and for some reason the --stdin option was not available on the version of passwd I was using (shipped in Ubuntu 14.04).

    If any of you happen to experience the same issue, you can work it around as I did, by using the chpasswd command like this:

    echo "<user>:<password>" | chpasswd
    
    0 讨论(0)
提交回复
热议问题