Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Install a perl script as a Win NT/2000/XP service.

by jryan (Vicar)
on Jan 27, 2003 at 22:23 UTC ( #230377=snippet: print w/ replies, xml ) Need Help??

Description: This perl script uses srvany and instsrv (two free programs from Microsoft; put on my perlmonk.org website for ease of linking) to install a perl script as a Windows NT/2000/XP service. Pretty handy, if you ask me.
#!perl -w
use strict;
use FindBin;
use Config;

while(1) {
    print "Please enter your script's name:\n";
    my $srvname = <>;
    chomp $srvname;
    my($srv) = $srvname =~ /^(\w+)/;

    if ($srv =~ /[a-z]\w+/i) {
        my $dir = $FindBin::Bin;
        $dir =~ s/\//\\\\/g;
        my $ret = `instsrv $srv $dir\\srvany.exe`;
        if ($ret =~ /success/i) {
            my $perlpath = $Config{perlpath};
            $perlpath =~ s/\\/\\\\/g;
            my $srvpath = $FindBin::Bin;
            $srvpath =~ s/(?<=\\)[^\\]+$//;
            $srvpath =~ s/\//\\\\/g;
            $srvpath .= "\\\\$srvname";

            my $reg = qq(
            REGEDIT4

                [HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Servic
+es\\)
                .$srvname.qq(\\Parameters]
                "Application"="$perlpath"
                "AppParameters"="$srvpath"
            );
            $reg =~ s/^\n//;
            my ($space) = $reg =~ /^(\s+)/;
            $reg =~ s/^$space//gm;

            open (OUT, ">reg.reg") or die $!;
            print OUT $reg."\n";
            close OUT;

            my $errormsg = qq(
                              Couldn't automatically add necessary inf
+ormation
                              to registry... generating necessary regi
+stry
                              file, please add manually by double-clic
+king on
                              it.
                             );
            $errormsg =~ s/(?<=\n)\s+//g;
            system ("reg.reg") and die $errormsg;
            unlink "reg.reg";
            print "\n\n$ret";
            exit 0;
        }
        else {
            die qq(Error installing $srvname as service: "$ret"\n);
        }
    }
    else {
        my $errormsg =  qq(
                           Error: Your script's name must start with a
+ letter,
                           and can only contain letters, numbers, and 
+the
                           underscore.  Please try again.
                          );
           $errormsg =~ s/(?<=\n)\s+//g;
        print $errormsg;
    }
}
Comment on Install a perl script as a Win NT/2000/XP service.
Download Code
Re: Install a perl script as a Win NT/2000/XP service.
by Aristotle (Chancellor) on Jan 28, 2003 at 01:45 UTC

      Could you care to elaborate? I see nothing in the node you point to that says "broken", only "bizarre." I've been using FindBin successfully for awhile now; can you give an example where it would break, especially in a script like this?

        I tried to use Win32::Daemon. I am using XP professional. Although I could install my perl script as a service, when I restarted my XP, the service never started. I checked the log in event viewer and it says "Timeout (30000 milliseconds) waiting for the Directory Monitoring Service service to connect." I tried running the example dirmon script from Dave Roth's site and it behaved in same way. My questions are 1) has dirmon script from dave roth's site worked for anybody on XP Pro. 2) My XP does not have XP service pack 1 on it. Do I need the service pack installed for this to work? 3) Or have I completely missed something. Thanks Jeevan Savant
Re: Install a perl script as a Win NT/2000/XP service.
by ibanix (Hermit) on Jan 28, 2003 at 03:10 UTC
    Very interesting.

    I prefer to compile my scripts with perl2exe and install the binary as a service. I've used instsrv and srvany, but I prefer to use the freely available FireDaemon. Get the v0.09 version -- the new version only supports 1 service without a registration code.

    You might also consider Win32::Daemon for a pure-perl solution.

    Update: Srvany.exe and instsrv.exe are part of the Windows NT 4.0 Resource Kit, available here.

    Cheers,
    ibanix

    $ echo '$0 & $0 &' > foo; chmod a+x foo; foo;
Re: Install a perl script as a Win NT/2000/XP service.
by AcidHawk (Vicar) on Jan 28, 2003 at 13:57 UTC

    Have you looked at the Win32::Daemon module.
    This can be compiled and installed without using any sryany.exe type service stubs..

    Example can be found here.

    -----
    Of all the things I've lost in my life, its my mind I miss the most.
Re: Install a perl script as a Win NT/2000/XP service.
by marinersk (Chaplain) on May 14, 2011 at 12:15 UTC

    I want to thank the original poster for dropping this node into PerlMonks.

    However, I've come to this node to drink many times over the past several years, and each time I came away without a functioning Windows Service.

    To be fair, the largest culprit was time available, followed closely on its heels by that demon I face with increasing frequency in my life: inability to focus.

    But yesterday, I broke through. The information on this node was key to breaking the ice. So, once again, many thanks to the original author.

    Unfortunately, the way I was able to break the ice was to take the perl script provided here and put debugging display statements after every step so I could see what it was trying to accomplish, then to pick and play with the things it tried to do and eventually adjusted all my incorrect perceptions and assumptions until they were in alignment with system expectations and -- voila! I had a functioning Perl script installed as a Windows Service.

    I am considering posting a completely functional do-it-yourself kit as a way to pave this path to the Windows Service tree in the gardens of the Monastery, that other visitors may find it more easily when they visit these hallowed grounds.

    The question is, would a fully working example of something which will take you from start to finish be of value, or is it better to force the Acolyte to earn his chops the way I did? Which approach better fits the ideology of the Monastery?

    Thoughts? Opinions?

      Personally, I like both. The step-by-step instructions, to reassure me that madness still hasn't caught up with me, and general directions to teach me about the way I'm going to take.

Re: Install a perl script as a Win NT/2000/XP service.
by marinersk (Chaplain) on May 16, 2011 at 16:51 UTC

    Okay, summary of steps based on reading a handful of web pages and dissecting jryan's Perl script at the top of this thread.

    This should be deployable almost as is. About the only things you should need to change are references to where the Perl binary is located and which directory into which you drop all files from this example. Global change and replace should be sufficient on these strings:

    • C:\\Perl\\bin\\perl.exe
    • C:\Steve\Dev\perlservice-perl
    • C:\\Steve\\Dev\\perlservice-perl

    Without further adieu:

    1. I wrote a Perl script which does something to confirm that the service ran the Perl script.
       perlservicetest.pl :
      #!/usr/bin/perl my $statim = time; open LOGFIL, ">>perlservicetest.log"; print LOGFIL "$statim perlservicetest START\n"; close LOGFIL; exit; __END__
    2. I created a registry file to set the parameters needed to make the service run. This was based almost entirely on jryan's script at the start of this thread.
       perlservicetest.reg :
      Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\perlservicetest\ +Parameters] "Application"="C:\\Perl\\bin\\perl.exe" "AppDirectory"="C:\\Steve\\Dev\\perlservice-perl" "AppParameters"="C:\\Steve\\Dev\\perlservice-perl\\perlservicetest.pl"

      (Don't forget the extra blank line at the end; it is not optional.)
      (Also -- where shown, the doubled backslashes are not optional.)
       
    3. I copied the  instsrv.exe  and  srvany.exe  files to the same directory as the Perl script.
       
    4. I created a batch file to install and start up the new service (which also ensures any old versions are first stopped and removed).

       perlservicetest-install.bat :

      @echo off echo ----------------------------------------------------------------- +-------------- echo Checking logfile contents echo ----------------------------------------------------------------- +-------------- type perlservicetest.log pause echo ----------------------------------------------------------------- +-------------- echo Checking service status echo ----------------------------------------------------------------- +-------------- sc qc "perlservicetest" pause echo ----------------------------------------------------------------- +-------------- echo Stopping old service echo ----------------------------------------------------------------- +-------------- net stop perlservicetest pause echo ----------------------------------------------------------------- +-------------- echo Removing old service echo ----------------------------------------------------------------- +-------------- instsrv perlservicetest remove sc qc "perlservicetest" pause echo ----------------------------------------------------------------- +-------------- echo Installing new service echo ----------------------------------------------------------------- +-------------- instsrv perlservicetest C:\Steve\Dev\perlservice-perl\srvany.exe sc qc "perlservicetest" pause echo ----------------------------------------------------------------- +-------------- echo Modifying new service parameters echo ----------------------------------------------------------------- +-------------- REM start /WAIT "Registry Update" perlservicetest.reg regedit /s C:\Steve\Dev\perlservice-perl\perlservicetest.reg pause echo ----------------------------------------------------------------- +-------------- echo Starting new service echo ----------------------------------------------------------------- +-------------- net start perlservicetest pause echo ----------------------------------------------------------------- +-------------- echo Checking logfile contents echo ----------------------------------------------------------------- +-------------- type perlservicetest.log echo ----------------------------------------------------------------- +--------------

    Then, to remove the service:

    1. I created a registry file to remove the service configuration information.
       perlservicetest-delete.reg :
      Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\perlservicetest\ +Parameters] "Application"=- "AppDirectory"=- "AppParameters"=- [-HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\perlservicetest +\Parameters] [-HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\perlservicetest +]

      (Again, remember -- the extra blank line at the end is not optional.)
       
    2. I created a batch file to stop and remove the service.
       perlservicetest-uninstall.bat :
      @echo off echo ----------------------------------------------------------------- +-------------- echo Checking logfile contents echo ----------------------------------------------------------------- +-------------- type perlservicetest.log pause echo ----------------------------------------------------------------- +-------------- echo Checking service status echo ----------------------------------------------------------------- +-------------- sc qc "perlservicetest" pause echo ----------------------------------------------------------------- +-------------- echo Stopping old service echo ----------------------------------------------------------------- +-------------- net stop perlservicetest pause echo ----------------------------------------------------------------- +-------------- echo Removing old service echo ----------------------------------------------------------------- +-------------- instsrv perlservicetest remove sc qc "perlservicetest" pause echo ----------------------------------------------------------------- +-------------- echo Removing service parameters echo ----------------------------------------------------------------- +-------------- regedit /s C:\Steve\Dev\perlservice-perl\perlservicetest-delete.reg echo ----------------------------------------------------------------- +--------------

    Once you have one that works, you can adjust individual components to customize it to your needs. Maybe you want  instsrv.exe  and  srvany.exe  to live somewhere common. Maybe you want to change the service name from  perlservicetest . Maybe you want the Perl script to do more than write lines to a log file.

    If the change you make doesn't give you the results you are looking for, roll back to the last one that worked, and keep chiseling away at it, back and forth, until you have molded it into your personal Windows Service masterpiece.

    :-)

Re: Install a perl script as a Win NT/2000/XP service.
by marmanold (Novice) on Jun 26, 2011 at 03:52 UTC

    None of the above worked for me on Windows 7 64-bit, but they did lead me in the right direction. The Non-Sucking Service Manager ended up being the key. Below is the code for the two .bat scripts needed to install a Perl script as a service in Windows 7 64-bit. It should also work in 32-bit versions, but I have not been able to test this yet.

    install_service.bat

    @echo off if defined %ProgramFiles(x86)% ( "%ProgramFiles(x86)%\path_to\your_app\service\nssm.exe" install my +Service "C:\Program Files (x86)\path_to\your_app\portable_perl\perl\b +in\perl.exe" """C:\Program Files (x86)\path_to\your_app\myService.pl" +"" ) else ( "%ProgramFiles%\path_to\your_app\service\nssm.exe" install myServi +ce "C:\Program Files\path_to\your_app\portable_perl\perl\bin\perl.exe +" """C:\Program Files\path_to\your_app\myService.pl""" ) net start myService exit

    remove_service.bat

    @echo off net stop myService if defined %ProgramFiles(x86)% ( "%ProgramFiles(x86)%\path_to\your_app\service\nssm.exe" remove myS +ervice confirm ) else ( "%ProgramFiles%\path_to\your_app\service\nssm.exe" remove myServic +e confirm ) exit

Back to Snippets Section

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://230377]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2014-09-18 21:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (124 votes), past polls