2016-04-25 26 views
1

我的程序應該添加100個用戶和密碼。然而,我有困難(我將發佈輸出和輸入文件)。應該發生的事情是用戶名是從文件中提取的,並且密碼也是這樣(來自他們的ID號)。格式將像用戶:jacob密碼:se-123456。但是,似乎用戶不存在。下面是我的程序:如何添加和刪除輸入文件中的用戶到linux系統?

#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 
+0

由於日誌表示您嘗試更改不存在用戶的密碼,因此如果您希望實際添加新用戶,則應該使用[useradd](http://linux.die.net/man/8/useradd)用戶 –

回答

0

你的評論了重要的線(如在由A.Flaischer註釋中):

anyCommand = "useradd " + name; 

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

你,另一方面程序似乎並沒有做什麼,你認爲它應該給。它從user0到user99工作,但你提到了示例輸入文件。該輸入文件將不會被正確處理。

由於C++可能是您最喜歡的語言,shell腳本將是完成您的任務的最簡單方法。

相關問題