How to Implement the Run As code in Python and C #

Source: Internet
Author: User

1. Introduce

Recently, due to project reasons, you need to switch user roles in the automated test code. Naturally, the first impression is that Run As is also called "running mode" in windows "). For example, you can right-click "running mode" when you open ie ":

Enter a new user account, for example:

My local machine uses the operating system logged on to the local account of the domain account, but now I need to use the domain account to run IE browser, so that I can open the corresponding page to bind the domain account permissions, for example, an internal company site. In this way, you do not need to enter the domain account name when you open the corresponding page.

Sometimes we can use the same method to start the corresponding application using the Administrator account:

In the near operating system, "Run as" is not in the right-click menu, but is changed to "Run As Administrator" to improve the user permissions for running the corresponding program:

Now, let's get down to the point. What I mentioned today is to use code to implement the same function, that is, to change the user account of the running program.

2. Run

Command Line

To use the command line to implement the preceding Run as function, you can write it like this:

Runas/user: user@domain.com "C: \ Program Files \ Internet Explorer \ ipolice.exe"

Python implementation

The content of RunAsWithinPython. py is as follows:

-->import os
os.system("runas /user:user@domain.com
 \"C:\Program Files\Internet Explorer\iexplore.exe\"")

The two lines seem to have less than a few characters than the command line content and have to surprise Python's strength. In addition, python uses indentation to represent the code hierarchy, rather than the braces "{" we use in C # and other languages. The code looks great. Of course, this is just a bit of gossip.

C # implementation 

The content of the Program. cs file is as follows:

using System.Diagnostics;
namespace MainTest
{
class Program
{   
public static void Main(string[] args)
{
System.Diagnostics.Process cmd = System.Diagnostics.Process.Start("runas", 
"/user:user@domain.com  \"C:\\Program Files\\Internet Explorer\\iexplore.exe\"");
}
}
}

Well, C # is doing well. It seems to be a simple command. If you didn't run the two programs, you might think it would be quite simple. But if you are a careful person or you have used the runas command line, you should know that there is a problem here:

Unfortunately, these two methods have a fatal defect: You can only enter the user name in the first command line before the system prompts you to enter the password, in this way, the user name and password cannot be completely included in a command line. In this way, we can only implement half of the code, and the other half still need to manually enter the password)-obviously this creates a half-pull project. You can also view the runas help instructions:

The purpose of this design is to prevent the weak people like us who want to use the command line to improve the permissions to run the program-at least we cannot use batch files to do this, this is safer, isn't it? Well, next, we will use another method, which will not cause the embarrassment of the above half-pull project.

3. Use ProcessStartInfo of Process to implement

Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Diagnostics;
Namespace MainTest
{
Class ProcessUserLogonHelper
{
///
/// Sample code for calling this method in the Main function
///
Private void InvokeExample ()
{
ProcessUserLogonHelper phelper = new ProcessUserLogonHelper ();
Process pro = phelper. createProcessWithUserToken (@ "C: \ Program Files \ Internet Explorer \ iexplore.exe", "bestreme.com", "chdwu ","************");
Pro. Start ();
}
 ///
/// Use the specified account to bind the process
///
/// Host Program of the process
/// Domain Name of the specified account
/// User Name of the specified account
/// Password of the specified account
/// Processes bound to a specific account
Public Process CreateProcessWithUserToken (string appPath, string domain, string userName, string password)
{
 Process pro = new Process ();
ProcessStartInfo processInfo = new ProcessStartInfo (appPath );
ProcessInfo. UseShellExecute = false;
ProcessInfo. UserName = userName;
ProcessInfo. Domain = domain;
System. Security. SecureString psw = new System. Security. SecureString ();
Foreach (char c in password. ToCharArray ())
{
Psw. AppendChar (c );
}
ProcessInfo. Password = psw;
ProcessInfo. WorkingDirectory = System. IO. Path. GetDirectoryName (appPath );
Pro. StartInfo = processInfo;
Return pro;
}
///
/// Use the specified account to bind the process
///
/// Host Program of the process
/// User Name of the Local Account
/// Password of the specified account
/// Processes bound to a specific account
Public Process CreateProcessWithUserToken (string appPath, string userName, string password)
{
Return CreateProcessWithUserToken (appPath, "", userName, password );
}
}
}

The code above has the following points:

1. Specify the corresponding startup path for the program to be run. Otherwise, the system may prompt "the directory does not exist" during the above Code running ";

2. You can assign a value to UserName directly using bestreme \ chdwu without setting the Domain;

3. Set UseShellExecute to False.

4. The password in ProcessStartInfo is of the System. Security. SecureString type. Therefore, if we only input a string as the password, we should convert it to the correct type.

Conclusion

The preceding describes several implementation methods of Run as. The first two methods use Python and C # To implement the command line Run as function, the third method is to add user information in ProcessStartInfo to start and run the application with the specified user.

Of course, there are many methods to implement the Run as code. In the next article, we will introduce the implementation of using Win32 APIs. It should be noted that there are some potential problems in using Win32 APIs. The details will be shown in the next article as soon as possible.

  1. Introduction to Python exception handling system
  2. Solve the problem of mixed errors in Chinese and English in Python
  3. How to compile Python code in Unix pipeline Style

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.