Меняем программно пароль локального пользователя

В рамках разработки системы программного удалённого администрирования, написал функцию смены пароля локального пользователя Windows, решил выложить, может кому пригодится.

История написания этой функции такова — однажды  у админов возникла необходимость сменить пароль локального пользователя Administrator на всех компах.  Проблема — обойти все 300 с лишним компов. Тогда и была написана эта функция и к ней агент выполняющий её на конечных компьютерах. Потом были добавлены и другие функции —  копирование/удаление файлов, модификация реестра, запуск программ, включение/отключение служб…

unit modChangePass;

interface

uses
  Windows, SysUtils;

function SetUserPassword(UserName, NewPassword: string; var ErrMsg: string;
  var UserNotFound: boolean): boolean;

implementation

const
  NetApi32 = 'netapi32.dll';

  NERR_Success      = 0;
  NERR_BASE         = 2100;
  NERR_UserNotFound = NERR_BASE + 121; // The user name could not be found.

type
  USER_INFO_1 = record
    usri1_name: PWideChar;
    usri1_password: PWideChar;
    usri1_password_age: DWORD;
    usri1_priv: DWORD;
    usri1_home_dir: PWideChar;
    usri1_comment: PWideChar;
    usri1_flags: DWORD;
    usri1_script_path: PWideChar;
  end;
  PUSER_INFO_1 = ^USER_INFO_1;

function NetUserGetInfo(servername, username: PWideChar;
  level: DWORD; var bufptr: PByte): DWORD; stdcall;
external netapi32 name 'NetUserGetInfo';

function NetUserSetInfo(servername, username: PWideChar;
  level: DWORD; buf: PByte; parm_err: PDWORD): DWORD; stdcall;
external netapi32 name 'NetUserSetInfo';

function NetApiBufferFree(Buffer: Pointer): DWORD; stdcall;
external netapi32 name 'NetApiBufferFree';

function Str2Wide(lpStr: String):PWideChar;
var
  dwStrlen : Cardinal;
begin
  dwStrLen := lstrlen(PChar(lpStr));
  GetMem(Result,(dwStrLen+1)*2);
  StringToWideChar(lpStr,Result,dwStrLen+1);
end;

function SetUserPassword(UserName, NewPassword: string; var ErrMsg: string; var UserNotFound: boolean): boolean;
var
  wname: PWideChar;
  parm_err: DWORD;
  ecode: integer;
  buf: PByte;
  u1: USER_INFO_1;
begin
  wname:=Str2Wide(UserName);

  try
    try
      ecode:=NetUserGetInfo(nil, wname, 1, buf);
      try
        result:=(ecode=NERR_SUCCESS);
        UserNotFound:=(ecode=NERR_UserNotFound);
        if not result then begin
          ErrMsg:=SysErrorMessage(ecode);
          exit;
        end;

        u1:=PUSER_INFO_1(buf)^;

        u1.usri1_password:=Str2Wide(NewPassword);
        try
          ecode:=NetUserSetInfo(nil, u1.usri1_name, 1, @u1, @parm_err);
          result:=(ecode=NERR_SUCCESS);
          if not result then
            ErrMsg:=SysErrorMessage(ecode);
        finally
          FreeMem(u1.usri1_password);
          u1.usri1_password:=nil;
        end;

      finally
        NetApiBufferFree(buf);
      end;
    finally
      FreeMem(wname);
    end;
  except
    on E:Exception do begin
      ErrMsg:=E.ClassName+': '+E.Message;
      Result:=false;
    end;
  end;
end;

end.

Писали ли Вы свои механизмы удаленного управления компьютером клиента?

Результат

Загрузка ... Загрузка ...

18.05.2010 · Ktf · 13 комментариев
Метки: , , , ,  · Рубрики: delphi, Ktf

13 комментариев

  1. Анонимус - 29.05.2010

    Str2Wide? А месье знает толк в извращениях…

    var
    WName: WideString;
    begin
    WName := UserName;

    NetUserGetInfo(nil, PWideChar(WName), 1, buf);

  2. Ktf - 29.05.2010

    Не возражаю

  3. Alexo - 12.06.2010

    История написания этой функции такова – однажды у админов возникла необходимость сменить пароль локального пользователя Administrator на всех компах.

    А как же скрипты AD

  4. yeezy boost 350 - 21.07.2018

    I simply needed to say thanks again. I do not know the things that I could possibly have carried out in the absence of those recommendations contributed by you over that field. It absolutely was a very troublesome situation for me personally, but viewing a new expert tactic you treated that forced me to leap for happiness. I’m grateful for this work and hope that you really know what a powerful job you happen to be carrying out training people today through your site. Probably you haven’t come across any of us.

  5. air max 90 - 22.07.2018

    I really wanted to send a note to appreciate you for those lovely pointers you are posting on this website. My considerable internet search has at the end of the day been paid with incredibly good points to share with my best friends. I would state that that most of us site visitors are extremely endowed to be in a good network with so many lovely people with insightful plans. I feel truly blessed to have come across the web site and look forward to really more entertaining times reading here. Thanks again for all the details.

  6. chrome hearts outlet - 22.07.2018

    I simply needed to appreciate you yet again. I’m not certain what I would have worked on without the actual thoughts revealed by you about such subject. It had been a real intimidating scenario for me personally, however , understanding the very expert mode you resolved it forced me to weep with contentment. Now i’m grateful for your guidance as well as hope that you realize what a great job your are accomplishing training men and women all through your website. Most likely you have never got to know any of us.

  7. Adidas NMD Runner Blue Green White - 22.07.2018

    An impressive share, I simply given this onto a colleague who was doing a little bit analysis on this. And he in fact bought me breakfast as a result of I found it for him.. smile. So let me reword that: Thnx for the deal with! But yeah Thnkx for spending the time to debate this, I really feel strongly about it and love studying more on this topic. If possible, as you turn into experience, would you mind updating your weblog with extra details? It is highly useful for me. Large thumb up for this blog publish!

  8. real jordans for sale cheap - 23.07.2018

    Thanks so much for giving everyone an exceptionally pleasant possiblity to discover important secrets from this website. It is usually very sweet and as well , stuffed with a great time for me personally and my office fellow workers to visit your blog no less than three times in a week to read through the fresh secrets you have. Of course, we’re certainly fulfilled considering the outstanding pointers you give. Some 4 tips on this page are undeniably the best I have had.

  9. lebron 15 - 24.07.2018

    I truly wanted to write down a small word so as to express gratitude to you for all the stunning guidelines you are giving at this site. My considerable internet investigation has at the end been compensated with incredibly good content to share with my pals. I would repeat that many of us readers actually are definitely blessed to exist in a perfect place with very many wonderful people with helpful tips. I feel extremely lucky to have come across the webpages and look forward to tons of more exciting minutes reading here. Thank you once more for a lot of things.

  10. kayno - 25.07.2018

    I truly wanted to write a comment in order to thank you for all the magnificent ways you are sharing at this website. My particularly long internet search has finally been rewarded with reasonable know-how to exchange with my relatives. I would repeat that many of us website visitors are very much fortunate to live in a good network with very many awesome individuals with interesting solutions. I feel very much grateful to have discovered your webpages and look forward to plenty of more fun times reading here. Thanks again for all the details.

  11. ray ban - 28.07.2018

    I would like to point out my love for your kind-heartedness in support of folks that absolutely need guidance on this area. Your real commitment to passing the solution all over had been remarkably practical and have usually allowed women like me to achieve their desired goals. Your entire warm and friendly facts entails much a person like me and much more to my office workers. Thank you; from everyone of us.

  12. yeezy 700 - 28.07.2018

    A lot of thanks for your own work on this web page. Gloria really likes conducting internet research and it’s really simple to grasp why. My partner and i learn all relating to the compelling method you offer very helpful steps on your website and therefore invigorate participation from visitors about this idea and our princess is undoubtedly starting to learn so much. Have fun with the rest of the year. You’re the one performing a really good job.

  13. pandora bracelet - 29.07.2018

    I actually wanted to write a quick note so as to thank you for the great hints you are giving out on this site. My extensive internet lookup has finally been honored with pleasant know-how to share with my company. I would express that we readers actually are very much endowed to be in a superb community with many wonderful people with helpful things. I feel very much grateful to have seen your webpages and look forward to plenty of more fun times reading here. Thanks once again for everything.