mystack
mystack

Reputation: 5522

Authenticate the Open function in python to create a file using Usename and Password

When I tried to create file to a shared folder I got an error Permission denied: ' tp create the file. I know a different username and password to create the file in that share folder. How can I use it with the Open function. The Open function I used is as given below.

with open(rootDirectory+"\\"+"test.txt", "a") as NewFile:
NewFile.write(filedata);

Thanks,

Upvotes: 1

Views: 875

Answers (1)

abarnert
abarnert

Reputation: 365965

There is no magical way to change the way you call open to do this for you. You have to interact with the Win32 security system in some way.


The first option is to impersonate the other user. Then, anything you do—including open, or anything else—is done as if you were that user. If you have pywin32, you can use its win32security wrappers to do this. You should read the MSDN docs on LogonUser, LogonUserEx, and ImpersonateLoggedOnUser to understand how this works. But it will look something like this:

user = LogonUser(username, None, password, 
                 LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT)
try:
    ImpersonateLoggedOnUser(user)
    with open(rootDirectory+"\\"+"test.txt", "a") as NewFile:
        NewFile.write(filedata)
finally:
    RevertToSelf()
    CloseHandler(user)

Of course you probably want some error handling, and you might want to create some context-manager wrappers instead of using a finally block, and so on. And again, read the docs to decide which function you want to call and which arguments you want to pass. But this should get you started.


As a variation on this, you can run a child process as that other user. That doesn't require impersonation (which you may not have the SeImpersonatePrivilege privileges to do). It's also much easier to port to Unix if you ever need to do that. See CreateProcessWithLogon for details.

A simpler way to do the same thing is to not do it from Python, but from the shell. Launch your script with the RunAs command instead of launching it directly. Or, if you can't do that, take the part that needs to run as the other user, move it into another script, then subprocess the RunAs command to launch it.


Alternatively, if you have sufficient rights (or can elevate to Administrator privileges to get those rights), you can just change the ACLs on the file to give yourself the write permission you don't have. In some cases, just doing os.chmod is sufficient for that, but usually not; you will have to pywin32 the native Win32 APIs again.

Upvotes: 2

Related Questions