【问题标题】:How can I make my bash script create an ssh key pair for a given user如何让我的 bash 脚本为给定用户创建一个 ssh 密钥对
【发布时间】:2022-10-21 03:15:54
【问题描述】:

我是 bash 脚本的新手。我编写了一个可以创建组和用户的脚本,它工作得很好,但我现在的挑战是如何让脚本为特定用户创建一个 ssh 密钥对。在我的脚本中,它在您切换到该用户后立即停止工作,并且不会继续创建 ssh 密钥对。

下面是我的脚本。

    for group in admin support engineering
    do
            sudo groupadd $group
            sudo useradd -m -s /bin/bash achebeh_${group}
    done
    sudo passwd achebeh_admin
    sudo su achebeh_admin
    ssh-keygen -t rsa

那么,我该如何使用这个脚本为 achebeh_admin 用户创建一个 ssh 对。我愿意学习。请这是我学习完教程课程后的第一个脚本。

【问题讨论】:

    标签: linux bash


    【解决方案1】:

    @Achebe-peter 如果我从您的简短描述中正确地得到了您的要求,这将为您完成工作。

    笔记:

    • 在测试环境中尝试此脚本,风险自负!
    • 假设您没有配置用户和相关文件,此脚本的性能最佳
    #!/bin/bash
    ### Configuration Parameters Start ###
    ## The username that doesn't exist and you want to create.
    user_name_prefix='testuser'
    
    ## The groups array that doesn't exist and you want to create and assign them to your user.
    groups=(testadmin testsupport testengineering)
    
    ## SSH-key lenght
    ssh_key_lenght='2048'
    ### Configuration Parameters End ###
    
    
    for group in ${groups[@]} ;do
      # Set username containing the prefix and group name
      user="${user_name_prefix}_${group}"
    
      # create such user if not exist
      getent passwd ${user} &>/dev/null
      if [ "$?" -ne 0 ] ;then
        sudo useradd -m -s /bin/bash "${user}"
    
        echo -e "
    Type password for: ${user}"
        sudo passwd ${user}
      fi
    
      # Create '.ssh' directory in user's home directory
      if ! [ -d /home/${user}/.ssh ] ;then
        sudo mkdir /home/${user}/.ssh
      fi
    
      # Generate ssh-key pair and move them to correspondig user's '.ssh/' dir.
      ssh_file_name="./${user}_ssh"
      (
      echo "${ssh_file_name}"
      echo ""
      echo "" 
      ) | ssh-keygen -t rsa -b ${ssh_key_lenght}
    
      sudo mv -i "${ssh_file_name}" "${ssh_file_name}.pub" /home/${user}/.ssh/
      sudo chown ${user}:${user} /home/${user}
    
      # Create the groups (if does not exist)
      getent group ${group} &>/dev/null
      if [ "$?" -ne 0 ] ;then
        sudo groupadd ${group}
      fi
    
      # Assign relevant group to the new user
      sudo usermod -aG ${group} ${user}
    done
    
    exit 0
    
    经测试
    GNU bash, version 5.0.17(1)-release (x86_64-pc-linux-gnu)
    Copyright (C) 2019 Free Software Foundation, Inc.
    License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
    

    PS。如果满足您的要求,请投票给我的答案并将其标记为正确答案。

    【讨论】:

      猜你喜欢
      • 2016-09-26
      • 2021-02-07
      • 2019-04-13
      • 2010-11-27
      • 1970-01-01
      • 2014-03-03
      • 1970-01-01
      • 1970-01-01
      • 2017-01-26
      相关资源
      最近更新 更多