Create directory and write files to a remote, password protected computer - python-2.7

What I would like to do is be able to gain access to a computer over the network so I can create a new directory there that I will then save multiple files to throughout the rest of the script.
I have a script that creates a bunch of files that I need to save. The problem is that this script may be ran off any number of computers, but needs to save to the same computer. If I manually remote connect to the computer it prompts me for a username and password, but I am trying to just create a directory there. My code is below, along with the response I get.
if not os.path.exists(self.dirIn):
tryPath = self.dirIn.split("/")[0:-1]
tryPath = '/'.join(tryPath)
if not os.path.exists(tryPath):
os.mkdir(tryPath)
os.mkdir(str(self.dirIn))
else:
os.mkdir(str(self.dirIn))
WindowsError: [Error 1326] The user name or password is incorrect: '//computer/e$/directory/I/am/creating'
I am using Windows, Python27

I was able to just map the drive to my computer using subprocess, do what I needed, and then unmap the drive (optional)
subprocess.Popen("net use E: \\\\computername\\E$ %s /USER:%s" % (password, username))
time.sleep(1) # Short delay to allow E: drive to map before continuing
if not os.path.exists(self.dirIn):
os.makedirs(self.dirIn)
subprocess.Popen("net use E: /delete")
I did run into problems without the sleep, my program wouldn't find the directory without it.

Related

Win32Com Error Running with Task Manager

I have a python script that calls open an Excel file, calls a macro in the file, then closes. If I run the file from the CLI, it works. If i put it in Task Scheduler, I get an error from win32com.
Method opening the Excel file:
import win32com.client as WinCom
if os.path.exists(reportGeneratorFileName):
try:
xl = WinCom.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename=os.path.abspath(reportGeneratorFileName))
xl.Application.Visible = False
xl.Application.Run("'{}'!Runner.Runner".format(reportGeneratorFileName))
l.info('Start Sleeping')
# Async mode of pythonw causes this to finish before the file is made
time.sleep(300)
l.info('Done Sleeping')
xl.Application.Quit()
except Exception as e:
l.error('Error updating file')
l.error(e, exc_info=True)
This is the Error i get:
06/04/2018 06:56:19 AM ERROR: (-2146959355, 'Server execution failed', None, None)
Traceback (most recent call last):
File "LAW Report.py", line 846, in createReport
xl = WinCom.Dispatch("Excel.Application")
File "c:\python27\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch
dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
File "c:\python27\lib\site-packages\win32com\client\dynamic.py", line 114, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
File "c:\python27\lib\site-packages\win32com\client\dynamic.py", line 91, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
com_error: (-2146959355, 'Server execution failed', None, None)
Now i am running 64 bit python 2.7 and 64 bit win32com while office is 32 bit, but as I said above, if I just run the script from the CLI it runs fine, just not from task manager. I am running this on a Windows Server 2012R2. I have tried configuring the task for 2008, 2008r2, and 2012r2. I also tried with highest privileges. I do need this to be able to run whether user is logged on or not. Everytime I have tested, the user has been logged on.
You need to
1) setup permissions in DCOMCnfg utility for user under which you're running -or-
2) change user to your desktop user account.
But first you need to get proper error code, not a generic message.
Pay attention that this should be considered as temporary solution since DCOM is badly supported by MS for automation as service. Consider switching to any library as soon as possible. There're numerous problems with Excel interop: you will have to reboot server from time to time, performance degradation with subsequent calls, you can't run Excels in parallel because of a good chance of errors, etc...
I encountered the same error of which my program can run from command prompt but not from task scheduler.
I solved this issue with these settings of task properties in task scheduler:
1. General->Security Options
a. make sure same user account you used to run python/microsoft program.
b. checked "Run only when user is logged on.
c. unchecked "Hidden"
For 1a, I'm using DOMAIN\userid that I used to login my laptop/PC.
This is the only way I found in order for the task scheduler to run successfully. Hope this helps.

Opening a file in the user's home directory

I've run into a strange problem using Core.In_channel library. Here's a piece of code meant to open a file in the user's home directory
open Core.Std
In_channel.with_file "~/.todo_list" ~f:(fun in_c ->
(* Do something here... *)
)
However, when running this, here is what I get:
Exception: (Sys_error "~/.todo_list: No such file or directory").
I am absolutely sure that ~/.todo_list exists, but I suspect that the filename is misinterpreted by OCaml.
What am I missing here?
As others have said, the expansion of ~ is done by the shell, not by the underlying system. No shell is involved in your call to with_file so the string is interpreted literally as a file name.
If the code is running on behalf of a user who has logged in, the home directory is available as the value of the environment variable HOME.
# Unix.getenv "HOME";;
- : string = "/Users/username"
Otherwise you will need to extract the home directory from the user database.
# let open Unix in (getpwnam "username").pw_dir;;
- : string = "/Users/username"

How to change permissoin of $Extend directory? Python? C++?

I want to hide a text file by moving it to $Extend directory (What is this directory?). So I run cmd as Administrator and run the below code :
C:\Windows\system32>copy I:\ToHide.txt I:\$Extend
Access is denied.
0 file(s) copied.
C:\Windows\system32>
As you see, I couldn't and I received Access Denied error. So I tried to takeown the destination directory ($Extend) and change its ACLs as below :
C:\Windows\system32>takeown /f I:\$Extend
SUCCESS: The file (or folder): "I:\$Extend" now owned by user "Abraham-VAIO\Abra
ham".
C:\Windows\system32>cacls I:\$Extend /G Abraham:F
Are you sure (Y/N)?Y
The system cannot find the file specified.
C:\Windows\system32>
Q1: Why cacls couldn't see this directory, while takeown could!?
After that, I use the below python code :
import win32api
import win32con
import win32security
FILENAME = "I:\\$Extend"
open (FILENAME, "w").close ()
print "I am", win32api.GetUserNameEx (win32con.NameSamCompatible)
sd = win32security.GetFileSecurity (FILENAME, win32security.OWNER_SECURITY_INFORMATION)
owner_sid = sd.GetSecurityDescriptorOwner ()
name, domain, type = win32security.LookupAccountSid (None, owner_sid)
print "File owned by %s\\%s" % (domain, name)
And I receive Access Denied again :
>>> ================================ RESTART ================================
>>>
Traceback (most recent call last):
File "C:\Users\Abraham\Desktop\teste.py", line 6, in <module>
open (FILENAME, "w").close ()
IOError: [Errno 13] Permission denied: 'I:\\$Extend'
>>>
Q2: Is this python code equal to takeown or it is an alternative for cacls?
Q3: Why I receive access denied,while I run idle (and after that python in command-line) as Administrator?
Last questions :
Q4: Why I can't open this directory using Windows Explorer, While I can open it using WinRAR? Does Windows restrict some APIs for Explorer but they are available for other softwares?
By the way, Is there any way to I achieve my goal using Python or C++ or ...? (Hiding something in $Extend directory)
In general, you can access the MFT directly by opening \.\PhysicalDriveX - which is the underlying physical disk (X is the number of the disk you want to open) - and then parse the disk directly, i.e. find the partition offset from the Master Boot Record, then parse the first NTFS sector and from there find the location of the MFT.
There is a great open source sample of how to parse the MFT in the ntfsfastfind project, see here:
http://home.comcast.net/~lang.dennis/console/ntfsfastfind/ntfsfastfind.html
I also recommend that you read about NTFS internals here:
http://technet.microsoft.com/en-us/library/cc781134(v=ws.10).aspx
http://ntfs.com/ntfs-mft.htm

Weird Behavior in Windows XP with Python snippet

I wrote a snippet that would automatically copy a file from a source directory to a path on an usb. Because drive letter names are assigned by the PC independent o the slot I figured I would GetLogicalDrives() and if the path to the usb directory is in any of those drives then it would copy (I hope I'm making some sense). Here is the piece of code I wrote in Python:
import itertools, ctypes, string, sys, os.path, shutil
def drive_list():
drive_bitmask = ctypes.cdll.kernel32.GetLogicalDrives()
drive_list = list(itertools.compress(string.ascii_uppercase,
map(lambda x:ord(x) - ord('0'), bin(drive_bitmask)[:1:-1])))
return drive_list
for drive in drive_list():
path = drive + ":\\targer_directory\target_file.ext"
if drive not in ["C", "D", "E"]:
if os.path.exists(path) == True:
shutil.copy2(r'C:\source_directory\source_file.ext', path)
Whenever I run this script I get a bunch of error messages saying:
"Exception Processing Message c0000013 Parameters 75b1bf7c 4 75b1bf7c 75b1bf7c"
I think this probably means that I have some "ghost drives" in my pc. Any help in bypassing this behavior is deeply appreciated.
Note: The code runs at the end and the copy job is done succesfuly, but not until the error messages are cleared which is not the objective if I want to perform automatic backups.
I'm not sure whether this will help or not. But you can try this!
We were receiving the same error on execution of a windows application (an .exe file) and the below steps resolved it.
Goto Registry Editor
(Run -> type 'regedit' -> hit enter)
Expand HKEY_LOCAL_MACHINE
Expand System
Expand CurrentControlSet
Expand Control
Select Windows
Double click on ErrorMode in the right side pane
Set the Value Data as 2
Click OK
Restart your system

Verify digital signature within system32/drivers folder

I've spent all night researching this without a solution.
I'm trying to verify the digital signature of a file in the drives folder (C:\Windows\System32\drivers*.sys) pick whatever one you want. I know that the code is correct because if you move the file from that folder to C:\ the test works.
WinVerifyTrust gives error 80092003
http://pastebin.com/nLR7rvZe
CryptQueryObject gives error 80092009
http://pastebin.com/45Ra6eL4
What's the deal?
0x80092003 = CRYPT_E_FILE_ERROR = An error occurred while reading or writing to the file.
0x80092009 = CRYPT_E_NO_MATCH = No match when trying to find the object.
I'm guessing you're running on a 64-bit machine and WOW64 file system redirection is redirecting you to syswow64\drivers, which is empty. You can disable redirection with Wow64DisableWow64FsRedirection().
if you right click and view properties of file can you see a digital signature? most likely your file is part of a catalogue and you need to use the catalogue API to extract the cert from cert DB and verify it.