一个操作本地或者远程主机服务的小程序

原创 2007年10月14日 12:33:00
////////////////////////////////////////////////////////////////////////////////
//
// Enum Service
//
// File : EnumService.cpp
//
//
// Create by : refdom
// Email : refdom@263.net
// Home Page : www.opengram.com
//
// If you modify the code, or add more functions, please email me a copy.
//
////////////////////////////////////////////////////////////////////////////////
#include "ConnectServer.h"
#include <stdio.h>
#include <windows.h>
#include <Winnetwk.h>
#include <Shlwapi.h>

#pragma comment(lib, "Advapi32.lib")
#pragma comment(lib, "Mpr.lib")

DWORD g_dwManagerAccess = SC_MANAGER_ALL_ACCESS;
DWORD g_dwServiceAccess = SERVICE_ALL_ACCESS;

void ListServices (SC_HANDLE, DWORD);
void MyStartService (SC_HANDLE, LPSTR);
void MyStopService (SC_HANDLE, LPSTR);
void MyViewService (SC_HANDLE, LPSTR);
void Usage(char*);

int main(int argc, char* argv[])
{
int nRetCode = 0;
char szIpc[50] = "";
DWORD dwServiceType;
SC_HANDLE schSCManager;
LPSTR lpUserName, lpPassword, lpServiceName;
NETRESOURCE NET;

if (argc < 2)
{
Usage(argv[0]);
return 0;
}

if (argv[1][0] == '/' && strlen(argv[1]) == 2)
{
switch (tolower(argv[1][1]))
{
case 'l':
dwServiceType = SERVICE_WIN32 | SERVICE_DRIVER;
break;
case 'd':
dwServiceType = SERVICE_DRIVER;
break;
case 'w':
dwServiceType = SERVICE_WIN32;
break;
case 'k':
dwServiceType = SERVICE_KERNEL_DRIVER;
break;
case 'f':
dwServiceType = SERVICE_FILE_SYSTEM_DRIVER;
break;
case 'o':
dwServiceType = SERVICE_WIN32_OWN_PROCESS;
break;
case 'h':
dwServiceType = SERVICE_WIN32_SHARE_PROCESS;
break;
case 'r':
dwServiceType = -1;
break;
case 's':
case 'p':
case 'v':
if (argc < 6 && (argc != 3))
{
printf ("Error! Input a service name!/n");
return 0;
}
else if (argc >6)
{
printf ("Error! A wrong service name!/n");
return 0;
}
break;
case '?':
Usage(argv[0]);
return 0;
default:
printf ("Error: Unknow option!/n");
return 0;;
}
}
else
{
printf ("Error: Unknow option!/n");
return 0;
}

//get service name
if (argc == 6)
{
lpServiceName = argv[5];
}
else if (argc == 3)
{
// if ((argv[2][0] != '//') && (argv[2][1] != '//'))
// {
if (argv[1][0] == '/' && strlen(argv[1]) == 2)
{
switch (tolower(argv[1][1]))
{
case 'l':
case 'd':
case 'w':
case 'k':
case 'f':
case 'o':
case 'h':
case 'r':
printf ("Error arguments!/n");
return 0;
default:
lpServiceName = argv[2];
break;
}
}
// lpServiceName = argv[2];
// }
}

if (argc > 3)
{
/* if ((argv[2][0] != '//') && (argv[2][1] != '//'))
{
schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
}
else
{
if (argc == 3)
{
lpUserName = "";
lpPassword = "";
//change access
g_dwManagerAccess = SC_MANAGER_CONNECT;
g_dwServiceAccess = GENERIC_READ;
sprintf (szIpc, "%s", argv[2]);
}
else
{
*/
lpUserName = argv[3];
lpPassword = argv[4];
sprintf (szIpc, "%s//ipc$", argv[2]);
// }

NET.lpLocalName = NULL;
NET.lpRemoteName = szIpc;
NET.dwType = RESOURCETYPE_ANY;
NET.lpProvider = NULL;

printf ("Connecting %s...",argv[2]);

nRetCode = MyConnectServer(&NET, lpPassword, lpUserName, CONNECT_INTERACTIVE, szIpc);
if (!nRetCode)
printf ("Successfully!/n");
else
{
printf ("Failed!/n");
}
schSCManager = OpenSCManager(argv[2], NULL, SC_MANAGER_ALL_ACCESS);
// }
}
else
{
schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
}

if (schSCManager == NULL)
{
printf ("%d/n", argc);
printf ("%d/n", GetLastError());
printf ("Open SCManager failed!/n");
return 0;
}

//
switch (tolower(argv[1][1]))
{
case 'l':
case 'd':
case 'w':
case 'k':
case 'f':
case 'o':
case 'h':
case 'r':
ListServices(schSCManager, dwServiceType);
break;
case 's':
MyStartService(schSCManager, lpServiceName);
break;
case 'p':
MyStopService(schSCManager, lpServiceName);
break;
case 'v':
MyViewService(schSCManager, lpServiceName);
break;
}

CloseServiceHandle(schSCManager);

if (argc >3 )
{
//close the session with remote server
printf ("/nDisconnecting server...");
nRetCode = MyDisConnectServer(szIpc, CONNECT_UPDATE_PROFILE, TRUE);
if (!nRetCode)
printf ("Successfully!/n");
else
printf ("Failed!/n");
}

return 0;
}

void ListServices(SC_HANDLE schSCManager, DWORD ServiceType)
{
//list services
LPENUM_SERVICE_STATUS_PROCESS lpServices;
DWORD n;
DWORD nSize = 0;
DWORD nServicesReturned;
DWORD nResumeHandle;
DWORD dwServiceType;
nResumeHandle = 0;
dwServiceType = ServiceType;
if (ServiceType == -1)
{
dwServiceType = SERVICE_WIN32;
}

lpServices = (LPENUM_SERVICE_STATUS_PROCESS) LocalAlloc(LPTR, 30720);

if (EnumServicesStatusEx(schSCManager, SC_ENUM_PROCESS_INFO,
dwServiceType, SERVICE_STATE_ALL,
(LPBYTE)lpServices, 30720,
&nSize, &nServicesReturned,
&nResumeHandle, NULL) == NULL)
{
printf ("Enum Error!%d/n",GetLastError());
return;
}
else
{
printf ("Listing service.../n/n");
}

printf ("------------------------------------------------------/n");
printf ("PID /t ServiceName {Service Display Name} <Current status>/n");
printf ("------------------------------------------------------/n");
for (n = 0; n < nServicesReturned; n++)
{
if (!(ServiceType == -1
&& lpServices[n].ServiceStatusProcess.dwCurrentState != SERVICE_RUNNING))
{
//Show the name of service
printf ("pid:%d.",lpServices[n].ServiceStatusProcess.dwProcessId);
if (lpServices[n].ServiceStatusProcess.dwProcessId == 0 )
{
printf ("/t");
}
printf ("%s/t{%s}", lpServices[n].lpServiceName, lpServices[n].lpDisplayName);
// printf ("/t");
//Show the status of service
switch (lpServices[n].ServiceStatusProcess.dwCurrentState)
{
case SERVICE_STOPPED:
printf ("<not running.>");
break;
case SERVICE_START_PENDING:
printf ("<starting.>");
break;
case SERVICE_STOP_PENDING:
printf ("<stopping.>");
break;
case SERVICE_RUNNING:
printf ("<running.>");
break;
case SERVICE_CONTINUE_PENDING:
printf ("<continue pending.>");
break;
case SERVICE_PAUSE_PENDING:
printf ("<pause pending.>");
break;
case SERVICE_PAUSED:
printf ("<paused.>");
break;
}
printf ("/n");
}
}
return;
}

void MyStartService(SC_HANDLE schSCManager, LPSTR lpServiceName)
{
SC_HANDLE schService;
DWORD dwWaitTime;
DWORD dwOldCheckPoint = 0;
DWORD dwStartTickCount;
SERVICE_STATUS ssStatus;
LPQUERY_SERVICE_CONFIG lpConfig;
DWORD dwSize;

schService = OpenService(schSCManager, lpServiceName, SERVICE_ALL_ACCESS);
if (schService == NULL)
{
printf ("Open service failed!/n");
return;
}

if (!QueryServiceStatus(schService, &ssStatus))
{
CloseServiceHandle(schService);
printf ("Query service status failed!/n");
return;
}
if (ssStatus.dwCurrentState == SERVICE_RUNNING
|| ssStatus.dwCurrentState == SERVICE_START_PENDING)
{
CloseServiceHandle(schService);
printf ("The service is running or starting!/n");
return;
}

lpConfig = (LPQUERY_SERVICE_CONFIG) LocalAlloc(LPTR, 1024);
if (!QueryServiceConfig(schService, lpConfig, 1024, &dwSize))
{
CloseServiceHandle(schService);
printf ("Query service config failed!/n");
return;
}
if (lpConfig->dwStartType == SERVICE_DISABLED)
{
printf ("The service is disabled!/n");
printf ("Try to change the service's start type...");
if (!ChangeServiceConfig(schService,
SERVICE_NO_CHANGE,
SERVICE_DEMAND_START,
SERVICE_NO_CHANGE,
NULL, NULL, NULL, NULL, NULL, NULL,NULL))
{
CloseServiceHandle(schService);
printf ("Failed!/n");
return;
}
else
printf ("Successfully!/n");
}

printf ("starting the service <%s>.../n", lpServiceName);
if (!StartService(schService, 0, NULL))
{
CloseServiceHandle(schService);
printf ("Starting the service failed!/n");
return;
}

if (!(QueryServiceStatus(schService, &ssStatus)))
{
CloseServiceHandle(schService);
printf ("Query service status failed!/n");
return;
}

while ( ssStatus.dwCurrentState == SERVICE_START_PENDING)
{
dwWaitTime = ssStatus.dwWaitHint / 10;
if( dwWaitTime < 1000 )
dwWaitTime = 1000;
else if ( dwWaitTime > 10000 )
dwWaitTime = 10000;
Sleep(dwWaitTime);

// Check the status again.
if (!QueryServiceStatus(
schService, // handle to service
&ssStatus) ) // address of structure
break;

if ( ssStatus.dwCheckPoint > dwOldCheckPoint )
{
// The service is making progress.
dwStartTickCount = GetTickCount();
dwOldCheckPoint = ssStatus.dwCheckPoint;
}
else
{
if(GetTickCount()-dwStartTickCount > ssStatus.dwWaitHint)
{
// No progress made within the wait hint
break;
}
}
}

if ( ssStatus.dwCurrentState == SERVICE_RUNNING )
{
printf ("Service is started successfully!/n");
}
else
{
printf ("Start service failed!/n");
}
return;
}

void MyStopService(SC_HANDLE schSCManager, LPSTR lpServiceName)
{
SC_HANDLE schService;
DWORD dwWaitTime;
SERVICE_STATUS ssStatus;

schService = OpenService(schSCManager, lpServiceName, SERVICE_ALL_ACCESS);
if (schService == NULL)
{
printf ("Open service failed!/n");
return;
}
if (!QueryServiceStatus(schService, &ssStatus))
{
printf ("Query service failed!/n");
CloseServiceHandle(schService);
return;
}

if (ssStatus.dwCurrentState == SERVICE_STOPPED
|| ssStatus.dwCurrentState == SERVICE_STOP_PENDING)
{
CloseServiceHandle(schService);
printf ("service is stopped!/n");
return;
}

printf ("stopping the service <%s>.../n", lpServiceName);
if (!(ControlService(schService, SERVICE_CONTROL_STOP, &ssStatus)))
{
CloseServiceHandle(schService);
printf ("Control service status failed!/n");
return;
}

dwWaitTime = ssStatus.dwWaitHint / 10;
if( dwWaitTime < 1000 )
dwWaitTime = 1000;
else if ( dwWaitTime > 10000 )
dwWaitTime = 10000;

Sleep(dwWaitTime);

if (!QueryServiceStatus(schService, &ssStatus))
{
printf ("Query service status failed!/n");
return;
}

if ( ssStatus.dwCurrentState == SERVICE_STOPPED || ssStatus.dwCurrentState == SERVICE_STOP_PENDING)
{
printf ("Service is stopped successfully!/n");
}
else
{
printf ("%d/n", ssStatus.dwCurrentState );
printf ("Service is not started!/n");
}
return;
}

void MyViewService(SC_HANDLE schSCManager, LPSTR lpServiceName)
{
SC_HANDLE schService;
LPSERVICE_STATUS_PROCESS lpStatus;
LPQUERY_SERVICE_CONFIG lpConfig;
LPSERVICE_DESCRIPTION lpDescription;
LPSERVICE_FAILURE_ACTIONS lpAction;
DWORD dwByteNeeded = 0;

lpStatus = (LPSERVICE_STATUS_PROCESS) LocalAlloc(LPTR, 1024);
lpConfig = (LPQUERY_SERVICE_CONFIG) LocalAlloc(LPTR, 1024);
lpDescription = (LPSERVICE_DESCRIPTION) LocalAlloc(LPTR, 1024);
lpAction = (LPSERVICE_FAILURE_ACTIONS) LocalAlloc(LPTR, 2048);
schService = OpenService(schSCManager, lpServiceName, g_dwServiceAccess);
if (schService == NULL)
{
printf ("Open service failed!/n");
return;
}

if (!QueryServiceStatusEx(schService, SC_STATUS_PROCESS_INFO,(LPBYTE) lpStatus, 1024, &dwByteNeeded))
{
CloseServiceHandle(schService);
printf ("Query service status failed!/n");
return;
}

printf ("/nView service: %s...",lpServiceName);
printf ("/n/tPID:%d", lpStatus->dwProcessId);
printf ("/n/tStatus:");
switch (lpStatus->dwCurrentState)
{
case SERVICE_STOPPED:
printf ("The service is not running.");
break;
case SERVICE_START_PENDING:
printf ("The service is starting.");
break;
case SERVICE_STOP_PENDING:
printf ("The service is stopping.");
break;
case SERVICE_RUNNING:
printf ("The service is running.");
break;
case SERVICE_CONTINUE_PENDING:
printf ("The service continue is pending.");
break;
case SERVICE_PAUSE_PENDING:
printf ("The service pause is pending.");
break;
case SERVICE_PAUSED:
printf ("The service is paused.");
break;
}
printf ("/n/tServiceType:");
switch (lpStatus->dwServiceType)
{
case SERVICE_FILE_SYSTEM_DRIVER:
printf ("The service is a file system driver.");
break;
case SERVICE_KERNEL_DRIVER:
printf ("The service is a kernel driver.");
break;
case SERVICE_WIN32_OWN_PROCESS:
printf ("The service runs in its own process.");
break;
case SERVICE_WIN32_SHARE_PROCESS:
printf ("The service shares a process with other services.");
break;
}

if(!QueryServiceConfig(schService, lpConfig, 1024, &dwByteNeeded))
{
CloseServiceHandle(schService);
printf ("Query service config failed!/n");
return;
}
printf ("/n/tDisplayName:%s", lpConfig->lpDisplayName );
printf ("/n/tPath:%s", lpConfig->lpBinaryPathName);
printf ("/n/tDependency:%s", lpConfig->lpDependencies );
printf ("/n/tLoadOrderGroup:%s", lpConfig->lpLoadOrderGroup );
printf ("/n/tStartType:");
switch (lpConfig->dwStartType)
{
case SERVICE_AUTO_START:
printf ("The service started automatically during system startup.");
break;
case SERVICE_BOOT_START:
printf ("The device driver started by the system loader. ");
break;
case SERVICE_DEMAND_START:
printf ("The service started need demand by a process.");
break;
case SERVICE_DISABLED:
printf ("The service that cannot be started.");
break;
case SERVICE_SYSTEM_START:
printf ("The device driver started by the IoInitSystem function.");
break;
}

if (!QueryServiceConfig2(schService, SERVICE_CONFIG_DESCRIPTION, (LPBYTE) lpDescription, 1024, &dwByteNeeded))
{
CloseServiceHandle(schService);
printf ("Query service's description failed!/n");
return;
}
printf ("/n/tDescription:%s", lpDescription->lpDescription);

if (!QueryServiceConfig2(schService, SERVICE_CONFIG_FAILURE_ACTIONS, (LPBYTE) lpAction, 2048, &dwByteNeeded))
{
CloseServiceHandle(schService);
printf ("Query service's action failed!/n");
return;
}
printf ("/n/tResetPeriod Time:%ds", lpAction->dwResetPeriod);
printf ("/n/tRebootMSG:%s", lpAction->lpRebootMsg);
printf ("/n/tCommand:%s", lpAction->lpCommand );
printf ("/n/tActions in the array:%d", lpAction->cActions );

printf ("/n");
LocalFree(lpStatus);
LocalFree(lpConfig);
LocalFree(lpDescription);
LocalFree(lpAction);
CloseServiceHandle(schService);
return;
}

void Usage(char* pchAppName)
{
printf ("**************************************************/n");
printf ("Service Application, by Refdom/n");
printf ("Email:refdom@263.net/n");
printf ("%s/n/n", pchAppName);
printf ("Description:ServiceApp.exe is used to enum services,start a service,stop a service./n");
printf ("/tIt can be used with both local or remote machine./n");
printf ("/tIf it's used with remote server, the username must be a administrator!/n");
printf ("Usage: ServiceApp.exe [option] {////server} {username} {password} {argument}/n");
printf ("option:/n");
printf ("/t/l/tList all services!/n");
printf ("/t/d/tList all DRVIERs!/n");
printf ("/t/w/tList all WIN32 services!/n");
printf ("/t/k/tList all KERNEL drivers!/n");
printf ("/t/f/tList all FILE drivers!/n");
printf ("/t/o/tList all OWN_PROCESS services!/n");
printf ("/t/h/tList all SHARE_PROCESS services!/n");
printf ("/t/r/tList all win32 running services!/n");
printf ("/t/s/tStart a service.The [argument] is the service's name/n");
printf ("/t/p/tStop a service.The [argument] is the service's name/n");
printf ("/t/v/tView a service status.The [argument] is the service's name/n");
printf ("Example:/n");
printf ("/tRemote Example:ServiceApp.exe /s ////server username password /"service name/"/n");
printf ("/tLocal Example:ServiceApp.exe /s /"service name/"/n");
printf ("/tLocal Example:ServiceApp.exe /l/n");
printf ("**************************************************/n");
}
 

Win7 计算机-右键-管理“该文件没有与之关联的程序来执行该操作”问题的解决方法

何解决Windows7"计算机"右键菜单中"管理"打不开问题   当单击"计算机"右键菜单中"管理"出现“该文件没有与之关联的程序来执行操作。请安装一个程序,或者,如果已安装程序,请在"默...
  • ashic
  • ashic
  • 2015年07月03日 09:13
  • 1925

监听总结之window服务本质和特点小结以及证明在window下监听程序其实就是多个(或是一个)监听配置的封装

同名进程都是一个程序(可执行文件exe)的复制,如任务管理器里的进程项里的svchost.exe,右键 转到服务后,右键属性看到 svchost.exe -k localsystemnetworkre...
  • haiross
  • haiross
  • 2013年11月07日 10:57
  • 2633

如何将linux一个程序作为一个服务

几个关键的说明: 1./etc/init.d/ 目录下的内容 里面都是放的shell script脚本,启动这些shell脚本就能够达到开启某些软件服务的目的,为什么是这个目录?这个是基因决定的,看...
  • qq383264679
  • qq383264679
  • 2016年02月16日 14:38
  • 1830

Python中字符串常见操作总结

Python中字符串常见操作总结:
  • u014745194
  • u014745194
  • 2017年04月13日 09:38
  • 636

BOF或EOF中有一个是“真”,或者当前的记录已被删除,所需的操作要求一个当前的记录。

运行时错误’3021‘; BOF或EOF中有一个是“真”,或者当前的记录已被删除,所需的操作要求一个当前的记录。 第一个:编码错了 第二种情况就是:它确实没有数据了。...
  • u010540106
  • u010540106
  • 2013年08月07日 15:56
  • 4797

VC 服务程序的编写

参考:http://msdn.microsoft.com/en-us/library/windows/desktop/bb540476(v=vs.85).aspx sample.h // T...
  • earbao
  • earbao
  • 2014年12月27日 20:58
  • 2026

windows服务程序开发详解

2014.06.11 前两天被要求将看门狗做成服务
  • rongxiaojun
  • rongxiaojun
  • 2014年06月11日 15:42
  • 2258

ORA-12541 TNS 无监听程序(数据库新建后,服务列表没有监听程序)

今天在同一台服务器上了装了 11g (已经就有了) 和 12c(新安装的)版本的oracle;12C安装完成,测试提示ORA-12541 TNS 无监听程序; 1、先检查,服务列表监听程序是否启动,...
  • lsyuan1989
  • lsyuan1989
  • 2015年12月28日 09:41
  • 3288

微信小程序教程(第三篇)

小程序的架构及实现机制,信道服务及会话管理   小程序架构及实现机制 小程序并不是 H5 应用,而是更偏向于传统的 CS 架构,它是基于数据驱动的模式,一切皆组件(视图组件)。所以建议在开发小程...
  • ailongyang
  • ailongyang
  • 2017年01月27日 20:38
  • 1326

windows服务监控和操作相关

代码中实现了删除服务,启动服务,停止服务,检测服务是否运行和服务是否存在等功能: #pragma once #include #include //删除服务 /* 返回:1:表示...
  • qingzai_
  • qingzai_
  • 2015年08月07日 10:49
  • 954
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:一个操作本地或者远程主机服务的小程序
举报原因:
原因补充:

(最多只允许输入30个字)