【问题标题】:bash script create users using csvbash 脚本使用 csv 创建用户
【发布时间】:2020-07-21 03:40:25
【问题描述】:

我正在尝试从 bash 中的 csv 文件创建不同的用户。 到目前为止,这是我的代码:

  #create arrays usernames and password 
  groups=(`cut -d: -f 1 "$filein"`) 
  usernames=(`cut -d: -f 3  "$filein" | tr [A-Z] [a-z] |awk '{print substr($1.$2}'`) 
  password=(`cut -d: -f 4 "$filein"`) 
  #creates the user accounts, adds them to groups, and sets passwords 
  #then once account is created 
  #checks if the group exists, if not then creates it 
  for group in ${groups[*]} 
  do 
  grep -q "^$group" /etc/group ; let x=$? 
  if [ $x -eq 1 ] 
  then 
  groupadd "$group" 
  fi 
  done 
  #creates the user accounts, adds them to groups, and sets passwords 
  #then once account is created 
  x=0 
  created=0 
  for user in ${usernames[*]} 
  do 
  useradd -n -c ${usernames[$x]} -g "${groups[$x]}" $user 2> /dev/null 
  chpasswd  "$user" > /dev/null 
  if [ $? -eq 0 ] 
  then 
  let created=$created+1 
  fi

由于某种原因,当我运行文件时,这是我得到的错误,甚至让我添加任何用户 groupadd: 'Q123456,Bob,Bob,QwertY1' 不是有效的组名 groupadd: 'Q236578,Jane,Jane,AzertY2' 不是有效的组名 任何帮助将不胜感激。谢谢你

【问题讨论】:

标签: linux bash csv passwords usergroups


【解决方案1】:

cut 命令中的分隔符是“:”而不是“,”

来自剪切手册页:

-d, --delimiter=DELIM

使用 DELIM 代替 TAB 作为字段分隔符

【讨论】:

  • 你的意思是用户名=(-d,DELIM: -f 3 "$filein" | tr [A-Z] [a-z] |awk '{print substr($1.$2}') ??
  • 我的意思是:> cut -d , 每次在此脚本中使用 cut 时,即剪切 -d , -f 1 "$filein"
  • 老实说,我是 bash 脚本的新手,我不太明白你会是这个样子吗?? usernames=cut -d( -f 3 "$filein" | tr [A-Z] [a-z] |awk '{print substr($1.$2})
  • 这 3 行应该解决问题 groups=(cut -d , -f 1 "$filein") usernames=(cut -d , -f 3 "$filein" | tr [A-Z] [a-z] |awk '{print substr($1.$2}') password=(cut -d , -f 4 "$filein") 解释:cut 命令中的 -d 开关是 wwitch to拆分字段。在您的示例(CSV)中,您的分隔符是 ,(逗号)。
  • 好的,现在做更多的降神会,我现在就试试谢谢,谢谢你的耐心