【问题标题】:How to add and delete users from input file to linux system?如何从输入文件到linux系统添加和删除用户?
【发布时间】:2016-04-25 21:45:20
【问题描述】:

我的程序应该添加 100 个用户和密码。但是我也遇到了困难(我将发布输出和输入文件)。应该发生的是从文件中获取用户名,并且密码也是如此(它来自他们的 ID 号)。格式类似于用户:jacob 密码:se-123456。但是,似乎用户不存在。这是我的程序:

#include <iostream>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;
int main()
{
cout << "Hello world." << endl;
//system("mkdir user1"); 
string anyCommand="", name, userpassword;
 ifstream myfile ("userNames1000.txt");
if (myfile.is_open())
   //code to open a file
 {
  while ( getline (myfile,anyCommand) )
    {
     for(int i = 0; i <= 100; i++)
            {

        stringstream temp;
        temp << i;
        name = "user";
        name += temp.str();  

        //useradd vs. userdel
        anyCommand = "useradd " + name;

        cout << anyCommand << endl;
        //system(anyCommand.c_str());

        anyCommand = ""; 
        userpassword = "se- " ;

         //set the command, e.g., system("echo john:se-2014 |chpasswd");
        anyCommand = "echo " + name + ":" + userpassword + " |chpasswd";
        cout << anyCommand << endl;
        system(anyCommand.c_str());

        }

        myfile.close();

        }


  }     
    else cout << "Unable to open file";

    return 0;


}

这是我运行程序时发生的情况:

    Hello World
    useradd user0
    echo user0:se-  | chpasswd
    chpasswd: line 1: user 'user0' does not exist
    chpasswd: error detected, changes ignored
    useradd user1
    echo user1:se-  | chpasswd
    chpasswd: line 1: user 'user1' does not exist
    chpasswd: error detected, changes ignored
    useradd user2
    echo user2:se-  | chpasswd
    chpasswd: line 1: user 'user2' does not exist
    chpasswd: error detected, changes ignored

然后一直持续到100;同样的错误继续存在。我有一种感觉,我正在朝着正确的方向前进,我只需要一些帮助来解决我需要解决的问题。

这是输入文件中的示例。

Mary:20153

Lindsey:19396

Ashley:17151

Jason:16861

【问题讨论】:

  • 正如日志所说,您尝试为不存在的用户更改密码,如果您想实际添加新用户,则应使用useradd

标签: c++ linux inputstream


【解决方案1】:

您注释掉了重要的一行(如 A.Flaischer 的评论中所述):

anyCommand = "useradd " + name;

cout << anyCommand << endl;
//system(anyCommand.c_str());

另一方面,您的程序似乎并没有按照您的想法去做。它适用于 user0 到 user99,但您提到了示例输入文件。将不会(正确)处理此输入文件。

由于 C++ 可能是您最喜欢的语言,因此 shell 脚本将是完成任务的最简单方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    相关资源
    最近更新 更多