How to change permissoin of $Extend directory? Python? C++? - 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

Related

PyDrive download file from a SHARED drive

I know how to use PyDrive to download a file from my drive, the problem is that I need to download (or at the very least OPEN) an xlsx file on a shared drive. Here is my code so far to download the file:
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LoadClientConfigFile('client_secret.json')
drive = GoogleDrive(gauth)
team_drive_id = 'XXXXX'
parent_folder_id = 'XXXXX'
file_id = 'XXXXX'
f = drive.CreateFile({
'id': file_id,
'parents': [{
'kind': 'drive#fileLink',
'teamDriveId': team_drive_id,
'id': parent_folder_id
}]
})
f.GetContentFile('<file_name>')
The code returns error 404 (file not found), which makes sense: when I check the URL that GetContentFile is looking at, it is the URL leading to my drive, not the shared drive. I am probably missing a 'supportsTeamDrives': True somewhere (but where?).
There is actually a post associated to my question on https://github.com/gsuitedevs/PyDrive/issues/149 where someone raised the exact same issue. Apparently, that brought a developer to modify PyDrive about two weeks ago, but I still don't understand how to interpret his modifications and how to fix my problem. I have not noticed any other similar post on Stack Overflow (not about downloading from a shared drive anyway). Any help would be deeply appreciated.
Kind regards,
Berti
I found an answer in a newer Github post: https://github.com/gsuitedevs/PyDrive/issues/160
Answer from SMB784 works: "supportsTeamDrives=True" should be added to files.py (pydrive package) on line 235-6.
This definitely fixed my issue.
Move from pydrive to pydrive2
After encountering the same problem, I ran into this comment on an issue within the googleworkspace/PyDrive GitHub page from 2020:
...there is an actively maintained version PyDrive2 (Travis tests, regular releases including conda) from the DVC.org team...please give it a try and let us know - https://github.com/iterative/PyDrive2
Moving from the pydrive package to the pydrive2 package enabled me to download a local copy of a file stored on a shared drive by only requiring me to know the file ID.
After installing pydrive2, you can download a local copy of the file within the shared drive by using the following code template:
# load necessary modules ----
from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive
# authenticate yourself using your credentials
gauth = GoogleAuth()
gauth.LoadClientConfigFile('client_secret.json')
drive = GoogleDrive(gauth)
# store the file ID of the file located within the shared drive
file_id = 'XXXXX'
# store the output file name
output_file_name = 'YYYYY'
# create an instance of Google Drive file with auth of this instance
f = drive.CreateFile({'id': file_id})
# save content of this file as a local file
f.GetContentFile(output_file_name)

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"

Can't open a file with a Japanese filename in Python

Why doesn't this work in the Python interpreter? I am running the Python 2.7 version of python.exe on Windows 7. My locale is en_GB.
open(u'黒色.txt')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 22] invalid mode ('r') or filename: u'??.txt'
The file does exist, and is readable.
And if I try
name = u'黒色.txt'
name
the interpreter shows
u'??.txt'
Additional:
Okay, I was trying to simplify my problem for the purposes of this forum. Originally the filename was arriving in a cgi script from a web page with a file picker. The idea was to let the web page user upload files to a server:
import cgi
form = cgi.FieldStorage()
fileItems = form['attachment[]']
for fileItem in fileItems:
if fileItem.file:
fileName = os.path.split(fileItem.filename)[1]
f = open(fileName, 'wb')
while True:
chunk = fileItem.file.read(100000)
if not chunk:
break
f.write(chunk)
f.close()
but the files created at the server side had corrupted names. I started investigating this in the Python interpreter, reproduced the problem (so I thought), and that is what I put into my original question. However, I think now that I managed to create a separate problem.
Thanks to the answers below, I fixed the cgi script by making sure the file name is treated as unicode:
fileName = unicode(os.path.split(fileItem.filename)[1])
I never got my example in the interpreter to work. I suspect that is because my PC has the wrong locale for this.
Here's an example script that reads and writes the file. You can use any encoding for the source file that supports the characters you are writing but make sure the #coding line matches. You can use any encoding for the data file as long as the encoding parameter matches.
#coding:utf8
import io
with io.open(u'黒色.txt','w',encoding='utf8') as f:
f.write(u'黒色.txt content')
with io.open(u'黒色.txt',encoding='utf8') as f:
print f.read()
Output:
黒色.txt content
Note the print will only work if the terminal running the script supports Japanese; otherwise, you'll likely get a UnicodeEncodeError. I am on Windows and use an IDE that supports UTF-8 output, since the Windows console uses a legacy US-OEM encoding that doesn't support Japanese.
Run IDLE if you want to work with Unicode strings interactively in Python. Then inputting or printing any characters will just work.

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

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.

Run LIWC as external program to python - subprocess

I would like to run LIWC (installed in my Mac) within a python 2.7 script.
I have been reading about subprocess (popen and check_output seem the way to go), but I do not get the syntax for:
opening the program;
getting a text file to be analysed;
running the program;
getting the output (analysis) and storing it in a text file.
This is my first approach to subprocess, is this possible?
I appreciate the suggestions.
EDIT
This is the closest to implementing a solution (still does not work):
I can open the application.
subprocess.call(['open', '/file.app'])
But cannot make it process the input file and get an output one.
subprocess.Popen(['/file.app', '-input', 'input.txt', '-output', 'output.txt'])
Nothing comes out of this code.
EDIT 2
After reading dozens of posts, I am still very confused about the syntax for the solution.
Following How do I pipe a subprocess call to a text file?
I came out with this code:
g = open('in_file.txt', 'rb', 0)
f = open('out_file.txt', 'wb')
subprocess.call(['open', "file.app"] stdin=g, stdout=f)
The output file comes out empty.
EDIT 3
Following http://www.cplusplus.com/forum/unices/40680/
When I run the following shell script on the Terminal:
cat input.txt | /Path/LIWC > output.txt
The output txt file is empty.
EDIT 4
When I run:
subprocess.check_call(['/PATH/LIWC', 'PATH/input.txt', 'PATH/output.txt'])
It opens LIWC, does not create an output file and freezes.
EDIT 5
When I run:
subprocess.call(['/PATH/LIWC', 'PATH/input.txt', 'PATH/output.txt'])
It runs LIWC, creates an empty output.txt file and freezes (the process does not end).
The problem with using 'open' in subprocess.call(['open', "file.app"] stdin=g, stdout=f) is that it requests that a file be opened through a service, and doesn't directly attach it to your python process. You'll need to instead use the path to LIWC. I'm not sure that it supports reading from stdin, though, so you might need to even pass in the path to the file you'd like it to open.