#include <windows.h>
#include <tchar.h>
#include <strsafe.h>
#include <aclapi.h>
#include <stdio.h>

#pragma comment(lib, "advapi32.lib")

TCHAR szCommand[10];
TCHAR szSvcName[80];

SC_HANDLE schSCManager;
SC_HANDLE schService;

VOID __stdcall DisplayUsage(void);

VOID __stdcall DoStartSvc(void);
VOID __stdcall DoUpdateSvcDacl(void);
VOID __stdcall DoStopSvc(void);

BOOL __stdcall StopDependentServices(void);

//
// Purpose:
// Entry point function. Executes specified command from user.
//
// Parameters:
// Command-line syntax is: svccontrol [command] [service_name]
//
// Return value:
// None
//
void _tmain(int argc, TCHAR *argv[])
{
printf("\n");
if( argc != 3 )
{
printf("ERROR: Incorrect number of arguments\n\n");
DisplayUsage();
return;
}

StringCchCopy(szCommand, 10, argv[1]);
StringCchCopy(szSvcName, 80, argv[2]);

if (lstrcmpi( szCommand, TEXT("start")) == 0 )
DoStartSvc();
else if (lstrcmpi( szCommand, TEXT("dacl")) == 0 )
DoUpdateSvcDacl();
else if (lstrcmpi( szCommand, TEXT("stop")) == 0 )
DoStopSvc();
else
{
_tprintf(TEXT("Unknown command (%s)\n\n"), szCommand);
DisplayUsage();
}
}

VOID __stdcall DisplayUsage()
{
printf("Description:\n");
printf("\tCommand-line tool that controls a service.\n\n");
printf("Usage:\n");
printf("\tsvccontrol [command] [service_name]\n\n");
printf("\t[command]\n");
printf("\t start\n");
printf("\t dacl\n");
printf("\t stop\n");
}

//
// Purpose:
// Starts the service if possible.
//
// Parameters:
// None
//
// Return value:
// None
//
VOID __stdcall DoStartSvc()
{
SERVICE_STATUS_PROCESS ssStatus;
DWORD dwOldCheckPoint;
DWORD dwStartTickCount;
DWORD dwWaitTime;
DWORD dwBytesNeeded;

// Get a handle to the SCM database.

schSCManager = OpenSCManager(
NULL, // local computer
NULL, // servicesActive database
STANDARD_RIGHTS_READ |
SC_MANAGER_CONNECT |
SC_MANAGER_ENUMERATE_SERVICE ); // full access rights

if (NULL == schSCManager)
{
printf("OpenSCManager failed (%d)\n", GetLastError());
return;
}

// Get a handle to the service.

schService = OpenService(
schSCManager, // SCM database
szSvcName, // name of service
SERVICE_QUERY_STATUS | SERVICE_START); // full access

if (schService == NULL)
{
printf("OpenService failed (%d)\n", GetLastError());
CloseServiceHandle(schSCManager);
return;
}

// Check the status in case the service is not stopped.

if (!QueryServiceStatusEx(
schService, // handle to service
SC_STATUS_PROCESS_INFO, // information level
(LPBYTE) &ssStatus, // address of structure
sizeof(SERVICE_STATUS_PROCESS), // size of structure
&dwBytesNeeded ) ) // size needed if buffer is too small
{
printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return;
}

// Check if the service is already running. It would be possible
// to stop the service here, but for simplicity this example just returns.

if(ssStatus.dwCurrentState != SERVICE_STOPPED && ssStatus.dwCurrentState != SERVICE_STOP_PENDING)
{
printf("Cannot start the service because it is already running\n");
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return;
}

// Save the tick count and initial checkpoint.

dwStartTickCount = GetTickCount();
dwOldCheckPoint = ssStatus.dwCheckPoint;

// Wait for the service to stop before attempting to start it.

while (ssStatus.dwCurrentState == SERVICE_STOP_PENDING)
{
// Do not wait longer than the wait hint. A good interval is
// one-tenth of the wait hint but not less than 1 second
// and not more than 10 seconds.

dwWaitTime = ssStatus.dwWaitHint / 10;

if( dwWaitTime < 1000 )
dwWaitTime = 1000;
else if ( dwWaitTime > 10000 )
dwWaitTime = 10000;

Sleep( dwWaitTime );

// Check the status until the service is no longer stop pending.

if (!QueryServiceStatusEx(
schService, // handle to service
SC_STATUS_PROCESS_INFO, // information level
(LPBYTE) &ssStatus, // address of structure
sizeof(SERVICE_STATUS_PROCESS), // size of structure
&dwBytesNeeded ) ) // size needed if buffer is too small
{
printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return;
}

if ( ssStatus.dwCheckPoint > dwOldCheckPoint )
{
// Continue to wait and check.

dwStartTickCount = GetTickCount();
dwOldCheckPoint = ssStatus.dwCheckPoint;
}
else
{
if(GetTickCount()-dwStartTickCount > ssStatus.dwWaitHint)
{
printf("Timeout waiting for service to stop\n");
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return;
}
}
}

// Attempt to start the service.

if (!StartService(
schService, // handle to service
0, // number of arguments
NULL) ) // no arguments
{
printf("StartService failed (%d)\n", GetLastError());
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return;
}
else printf("Service start pending...\n");

// Check the status until the service is no longer start pending.

if (!QueryServiceStatusEx(
schService, // handle to service
SC_STATUS_PROCESS_INFO, // info level
(LPBYTE) &ssStatus, // address of structure
sizeof(SERVICE_STATUS_PROCESS), // size of structure
&dwBytesNeeded ) ) // if buffer too small
{
printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return;
}

// Save the tick count and initial checkpoint.

dwStartTickCount = GetTickCount();
dwOldCheckPoint = ssStatus.dwCheckPoint;

while (ssStatus.dwCurrentState == SERVICE_START_PENDING)
{
// Do not wait longer than the wait hint. A good interval is
// one-tenth the wait hint, but no less than 1 second and no
// more than 10 seconds.

dwWaitTime = ssStatus.dwWaitHint / 10;

if( dwWaitTime < 1000 )
dwWaitTime = 1000;
else if ( dwWaitTime > 10000 )
dwWaitTime = 10000;

Sleep( dwWaitTime );

// Check the status again.

if (!QueryServiceStatusEx(
schService, // handle to service
SC_STATUS_PROCESS_INFO, // info level
(LPBYTE) &ssStatus, // address of structure
sizeof(SERVICE_STATUS_PROCESS), // size of structure
&dwBytesNeeded ) ) // if buffer too small
{
printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
break;
}

if ( ssStatus.dwCheckPoint > dwOldCheckPoint )
{
// Continue to wait and check.

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

// Determine whether the service is running.

if (ssStatus.dwCurrentState == SERVICE_RUNNING)
{
printf("Service started successfully.\n");
}
else
{
printf("Service not started. \n");
printf(" Current State: %d\n", ssStatus.dwCurrentState);
printf(" Exit Code: %d\n", ssStatus.dwWin32ExitCode);
printf(" Check Point: %d\n", ssStatus.dwCheckPoint);
printf(" Wait Hint: %d\n", ssStatus.dwWaitHint);
}

CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
}

//
// Purpose:
// Updates the service DACL to grant start, stop, delete, and read
// control access to the Guest account.
//
// Parameters:
// None
//
// Return value:
// None
//
VOID __stdcall DoUpdateSvcDacl()
{
EXPLICIT_ACCESS ea;
SECURITY_DESCRIPTOR sd;
PSECURITY_DESCRIPTOR psd = NULL;
PACL pacl = NULL;
PACL pNewAcl = NULL;
BOOL bDaclPresent = FALSE;
BOOL bDaclDefaulted = FALSE;
DWORD dwError = 0;
DWORD dwSize = 0;
DWORD dwBytesNeeded = 0;

// Get a handle to the SCM database.

schSCManager = OpenSCManager(
NULL, // local computer
NULL, // ServicesActive database
STANDARD_RIGHTS_READ |
SC_MANAGER_CONNECT |
SC_MANAGER_ENUMERATE_SERVICE); // full access rights

if (NULL == schSCManager)
{
printf("OpenSCManager failed (%d)\n", GetLastError());
return;
}

// Get a handle to the service

schService = OpenService(
schSCManager, // SCManager database
szSvcName, // name of service
READ_CONTROL | WRITE_DAC); // access

if (schService == NULL)
{
printf("OpenService failed (%d)\n", GetLastError());
CloseServiceHandle(schSCManager);
return;
}

// Get the current security descriptor.

if (!QueryServiceObjectSecurity(schService,
DACL_SECURITY_INFORMATION,
&psd, // using NULL does not work on all versions
0,
&dwBytesNeeded))
{
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
dwSize = dwBytesNeeded;
psd = (PSECURITY_DESCRIPTOR)HeapAlloc(GetProcessHeap(),
HEAP_ZERO_MEMORY, dwSize);
if (psd == NULL)
{
// Note: HeapAlloc does not support GetLastError.
printf("HeapAlloc failed\n");
goto dacl_cleanup;
}

if (!QueryServiceObjectSecurity(schService,
DACL_SECURITY_INFORMATION, psd, dwSize, &dwBytesNeeded))
{
printf("QueryServiceObjectSecurity failed (%d)\n", GetLastError());
goto dacl_cleanup;
}
}
else
{
printf("QueryServiceObjectSecurity failed (%d)\n", GetLastError());
goto dacl_cleanup;
}
}

// Get the DACL.

if (!GetSecurityDescriptorDacl(psd, &bDaclPresent, &pacl,
&bDaclDefaulted))
{
printf("GetSecurityDescriptorDacl failed(%d)\n", GetLastError());
goto dacl_cleanup;
}

// Build the ACE. GUEST

BuildExplicitAccessWithName(&ea, TEXT("EVERYONE"),
SERVICE_START | SERVICE_STOP | READ_CONTROL | DELETE,
SET_ACCESS, CONTAINER_INHERIT_ACE);

dwError = SetEntriesInAcl(1, &ea, pacl, &pNewAcl);
if (dwError != ERROR_SUCCESS)
{
printf("SetEntriesInAcl failed(%d)\n", dwError);
goto dacl_cleanup;
}

// Initialize a new security descriptor.

if (!InitializeSecurityDescriptor(&sd,
SECURITY_DESCRIPTOR_REVISION))
{
printf("InitializeSecurityDescriptor failed(%d)\n", GetLastError());
goto dacl_cleanup;
}

// Set the new DACL in the security descriptor.

if (!SetSecurityDescriptorDacl(&sd, TRUE, pNewAcl, FALSE))
{
printf("SetSecurityDescriptorDacl failed(%d)\n", GetLastError());
goto dacl_cleanup;
}

// Set the new DACL for the service object.

if (!SetServiceObjectSecurity(schService,
DACL_SECURITY_INFORMATION, &sd))
{
printf("SetServiceObjectSecurity failed(%d)\n", GetLastError());
goto dacl_cleanup;
}
else printf("Service DACL updated successfully\n");

dacl_cleanup:
CloseServiceHandle(schSCManager);
CloseServiceHandle(schService);

if(NULL != pNewAcl)
LocalFree((HLOCAL)pNewAcl);
if(NULL != psd)
HeapFree(GetProcessHeap(), 0, (LPVOID)psd);
}

//
// Purpose:
// Stops the service.
//
// Parameters:
// None
//
// Return value:
// None
//
VOID __stdcall DoStopSvc()
{
SERVICE_STATUS_PROCESS ssp;
DWORD dwStartTime = GetTickCount();
DWORD dwBytesNeeded;
DWORD dwTimeout = 30000; // 30-second time-out
DWORD dwWaitTime;

// Get a handle to the SCM database.

schSCManager = OpenSCManager(
NULL, // local computer
NULL, // ServicesActive database
STANDARD_RIGHTS_READ |
SC_MANAGER_CONNECT |
SC_MANAGER_ENUMERATE_SERVICE ); // full access rights

if (NULL == schSCManager)
{
printf("OpenSCManager failed (%d)\n", GetLastError());
return;
}

// Get a handle to the service.

schService = OpenService(
schSCManager, // SCM database
szSvcName, // name of service
SERVICE_STOP |
SERVICE_QUERY_STATUS |
SERVICE_ENUMERATE_DEPENDENTS);

if (schService == NULL)
{
printf("OpenService failed (%d)\n", GetLastError());
CloseServiceHandle(schSCManager);
return;
}

// Make sure the service is not already stopped.

if ( !QueryServiceStatusEx(
schService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded ) )
{
printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
goto stop_cleanup;
}

if ( ssp.dwCurrentState == SERVICE_STOPPED )
{
printf("Service is already stopped.\n");
goto stop_cleanup;
}

// If a stop is pending, wait for it.

while ( ssp.dwCurrentState == SERVICE_STOP_PENDING )
{
printf("Service stop pending...\n");

// Do not wait longer than the wait hint. A good interval is
// one-tenth of the wait hint but not less than 1 second
// and not more than 10 seconds.

dwWaitTime = ssp.dwWaitHint / 10;

if( dwWaitTime < 1000 )
dwWaitTime = 1000;
else if ( dwWaitTime > 10000 )
dwWaitTime = 10000;

Sleep( dwWaitTime );

if ( !QueryServiceStatusEx(
schService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded ) )
{
printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
goto stop_cleanup;
}

if ( ssp.dwCurrentState == SERVICE_STOPPED )
{
printf("Service stopped successfully.\n");
goto stop_cleanup;
}

if ( GetTickCount() - dwStartTime > dwTimeout )
{
printf("Service stop timed out.\n");
goto stop_cleanup;
}
}

// If the service is running, dependencies must be stopped first.

StopDependentServices();

// Send a stop code to the service.

if ( !ControlService(
schService,
SERVICE_CONTROL_STOP,
(LPSERVICE_STATUS) &ssp ) )
{
printf( "ControlService failed (%d)\n", GetLastError() );
goto stop_cleanup;
}

// Wait for the service to stop.

while ( ssp.dwCurrentState != SERVICE_STOPPED )
{
Sleep( ssp.dwWaitHint );
if ( !QueryServiceStatusEx(
schService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded ) )
{
printf( "QueryServiceStatusEx failed (%d)\n", GetLastError() );
goto stop_cleanup;
}

if ( ssp.dwCurrentState == SERVICE_STOPPED )
break;

if ( GetTickCount() - dwStartTime > dwTimeout )
{
printf( "Wait timed out\n" );
goto stop_cleanup;
}
}
printf("Service stopped successfully\n");

stop_cleanup:
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
}

BOOL __stdcall StopDependentServices()
{
DWORD i;
DWORD dwBytesNeeded;
DWORD dwCount;

LPENUM_SERVICE_STATUS lpDependencies = NULL;
ENUM_SERVICE_STATUS ess;
SC_HANDLE hDepService;
SERVICE_STATUS_PROCESS ssp;

DWORD dwStartTime = GetTickCount();
DWORD dwTimeout = 30000; // 30-second time-out

// Pass a zero-length buffer to get the required buffer size.
if ( EnumDependentServices( schService, SERVICE_ACTIVE,
lpDependencies, 0, &dwBytesNeeded, &dwCount ) )
{
// If the Enum call succeeds, then there are no dependent
// services, so do nothing.
return TRUE;
}
else
{
if ( GetLastError() != ERROR_MORE_DATA )
return FALSE; // Unexpected error

// Allocate a buffer for the dependencies.
lpDependencies = (LPENUM_SERVICE_STATUS) HeapAlloc(
GetProcessHeap(), HEAP_ZERO_MEMORY, dwBytesNeeded );

if ( !lpDependencies )
return FALSE;

__try {
// Enumerate the dependencies.
if ( !EnumDependentServices( schService, SERVICE_ACTIVE,
lpDependencies, dwBytesNeeded, &dwBytesNeeded,
&dwCount ) )
return FALSE;

for ( i = 0; i < dwCount; i++ )
{
ess = *(lpDependencies + i);
// Open the service.
hDepService = OpenService( schSCManager,
ess.lpServiceName,
SERVICE_STOP | SERVICE_QUERY_STATUS );

if ( !hDepService )
return FALSE;

__try {
// Send a stop code.
if ( !ControlService( hDepService,
SERVICE_CONTROL_STOP,
(LPSERVICE_STATUS) &ssp ) )
return FALSE;

// Wait for the service to stop.
while ( ssp.dwCurrentState != SERVICE_STOPPED )
{
Sleep( ssp.dwWaitHint );
if ( !QueryServiceStatusEx(
hDepService,
SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssp,
sizeof(SERVICE_STATUS_PROCESS),
&dwBytesNeeded ) )
return FALSE;

if ( ssp.dwCurrentState == SERVICE_STOPPED )
break;

if ( GetTickCount() - dwStartTime > dwTimeout )
return FALSE;
}
}
__finally
{
// Always release the service handle.
CloseServiceHandle( hDepService );
}
}
}
__finally
{
// Always free the enumeration buffer.
HeapFree( GetProcessHeap(), 0, lpDependencies );
}
}
return TRUE;
}

win7 提升windows服务权限使非管理员用户可以控制windows服务的开启和关闭的更多相关文章

  1. 如何设置非管理员用户配置特定的IIS站点

    如何设置非管理员用     户配置特定的IIS站点 一.           添加IIS管理服务 二.           启动管理服务 勾选启用远程连接后.点右边的应用 三.           设 ...

  2. centos7新增用户并授权root权限、非root用户启动tomcat程序

    一.centos7新增用户并授权root权限 cat /etc/redhat-release查看centos版本号 1.禁用root账户登录 vim /etc/ssh/sshd_config 找到这一 ...

  3. win7如何设置某个软件不弹出用户账户控制

    手动修改注册表: 在 HKEY_CURRENT_USERS\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers 键下面 ...

  4. 别再让你的微服务裸奔了,基于 Spring Session &amp; Spring Security 微服务权限控制

    微服务架构 网关:路由用户请求到指定服务,转发前端 Cookie 中包含的 Session 信息: 用户服务:用户登录认证(Authentication),用户授权(Authority),用户管理(R ...

  5. 计划任务中使用NT AUTHORITY\SYSTEM用户和普通管理员用户有什么差别

    原文地址:http://www.ynufe.edu.cn/metc/Article/ShowArticle.asp?ArticleID=805 系统管理员会碰到这种问题,为什么在更改系统登录用户pas ...

  6. 非root用户执行程序---sudo的使用

    场景 在应用部署过程中,会遇到这样的问题:前期需要root用户执行配置.初始化工作,而具体的业务应用需要使用非root用户启动. 如何解决呢? 方法 可以使用sudo,实现授权. sudo命令授权,既 ...

  7. 非root用户使用1024以下端口

      如果你有一个最新的内核,确实有可能使用它作为非root用户启动服务,但绑定低端口.最简单有效的办法是: #setcap 'cap_net_bind_service=+ep' /path/to/pr ...

  8. windows7安装phpnow Apache非管理员权限不能操作Windows NT服务的解决方法

    科普一下:PHPnow 是什么?        Win32 下绿色免费的 Apache + PHP + MySQL 环境套件包.简易安装.快速搭建支持虚拟主机的 PHP 环境,可以安装 Discuz! ...

  9. windows下非管理员权限安装mysql

    windows下,mysql有两种安装方式: 1.msi安装 2.zip安装 无论是哪种安装方式,都因为需要将mysql安装为一个服务,所以必须要以管理员权限安装. 因为公司的换了虚拟机,无法取得管理 ...

随机推荐

  1. iOS,几种设计模式

    1.单例模式 2.观察者模式 3.委托代理 4.block回调 5.反射机制 单例模式 iOS单例模式的2种方式.根据线程安全的实现来区分,一种是使用@synchronized ,另一种是使用GCD的 ...

  2. hdu4968

    题目链接:http://acm.split.hdu.edu.cn/showproblem.php?pid=4968 说是考dp,但是我没出来dp在哪,可能贪心思想更多一些吧. AC代码: #inclu ...

  3. Maven概要[转]

    1. Maven介绍 1.1. 简介 java编写的用于构建系统的自动化工具. 目前版本是2.0.9,注意maven2和maven1有很大区别,阅读第三方文档时需要区分版本. 1.2. Maven资源 ...

  4. CentOS 6.4安装搭建Tomcat 7

    1.检查java版本信息 java -versionjava version "1.7.0_65"OpenJDK Runtime Environment (rhel-2.5.1.2 ...

  5. BLOB二进制对象(blob.c/h)

    BLOB二进制对象(blob.c/h) 数据结构 struct blob_attr { uint32_t id_len; /** 高1位为extend标志,高7位存储id, * 低24位存储data的 ...

  6. Xcode工程使用CocoaPods管理第三方库新建工程时出现异常

    Xcode工程使用CocoaPods管理第三方库新建工程时出现异常 Xcode工程使用CocoaPods管理第三方库新建工程时出现错误工程使用CocoaPods管理第三方库,在新的目录update版本 ...

  7. 关机和重启Linux命令

    常用命令: shoutdown -h 10  十分钟后关机 shoutdown -r  10  十分钟重启 shoutdow -h now 立刻关机 shoutdow -r now 立刻重启 不安全的 ...

  8. Unity UGUI

    超详细的基础教程传送门:(持续更新中) Unity UGUI之Canvas&EventSystem:http://blog.csdn.net/qq992817263/article/detai ...

  9. 如何查找Linux服务器上JDK安装路径?

    成功远程到你要部署软件的Linux服务器上.这是第一步. 查看JDK版本:java -version 查看java执行路径:which java 查看JAVA_HOME路径:echo $JAVA_HO ...

  10. 猥琐百度杯猥琐CTF

    其实不难,但是作为我这个代码菜鸡+脑洞菜鸡+黑阔菜鸡而言确实挺难. 题目源码: <?php error_reporting(0); session_start(); require('./fla ...