analitics

Pages

Showing posts with label sys. Show all posts
Showing posts with label sys. Show all posts

Tuesday, January 16, 2024

News : How to use ShellExecuteA with Python programming language.

I just discovery this option to use ShellExecuteA in Python.
Let's see some example:
import ctypes
import sys

def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

if not is_admin():
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
... and another example:
import sys
import ctypes

#fix unicode access
import sys
if sys.version_info[0] >= 3:
    unicode = str

def run_as_admin(argv=None, debug=False):
    shell32 = ctypes.windll.shell32
    if argv is None and shell32.IsUserAnAdmin():
        return True    
    if argv is None:
        argv = sys.argv
    if hasattr(sys, '_MEIPASS'):
        # Support pyinstaller wrapped program.
        arguments = map(unicode, argv[1:])
    else:
        arguments = map(unicode, argv)
    argument_line = u' '.join(arguments)
    executable = unicode(sys.executable)
    if debug:
        print('Command line: ', executable, argument_line)
    ret = shell32.ShellExecuteW(None, u"runas", executable, argument_line, None, 1)
    if int(ret) <= 32:
        return False
    return None  

if __name__ == '__main__':
    ret = run_as_admin()
    if ret is True:
        print ('I have admin privilege.')
        input('Press ENTER to exit.')
    elif ret is None:
        print('I am elevating to admin privilege.')
        input('Press ENTER to exit.')
    else:
        print('Error(ret=%d): cannot elevate privilege.' % (ret, ))

Tuesday, November 19, 2019

Python 3.7.5 : Display a file in the hexadecimal and binary output.

This is an example with a few python3 modules that display a file in the hexadecimal and binary output:
import sys
import os.path
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("FILE", help="the file that you wish to dump to hexadecimal", type=str)
parser.add_argument("-b", "--binary", help="display bytes in binary format instead of hexadecimal")
args = parser.parse_args()

try:
    with open(args.FILE, "rb") as f:
        n = 0
        b = f.read(16)
        while b:
            if not args.binary:
                s1 = " ".join([format(i,'02x') for i in b])
                s1 = s1[0:23] + " " + s1[23:]
                width = 48
            else:
                s1 = " ".join([format(i,'08b') for i in b])
                s1 = s1[0:71] + " " + s1[71:]
                width = 144
            s2 = "".join([chr(i) if 32 <= i <= 127 else "." for i in b])
            print(format(n * 16,'08x'), format(s1), format(s2))
            n += 1
            b = f.read(16)

    print(format(os.path.getsize(args.FILE),'08x'))

except Exception as e:
    print(__file__, ": ", type(e).__name__, " - ", e, sep="", file=sys.stderr)
The hexadecimal output of the sec.png file:
[mythcat@desk test]$ python3 hex.py sec.png 
00000000 89 50 4e 47 0d 0a 1a 0a  00 00 00 0d 49 48 44 52 .PNG........IHDR
00000010 00 00 01 0b 00 00 00 bd  08 03 00 00 00 93 6f a8 ..............o.
00000020 bc 00 00 00 5d 50 4c 54  45 ff ff ff ab ab ab fc ....]PLTE.......
00000030 fc fc a0 a0 a0 f5 f5 f5  a6 a6 a6 f9 f9 f9 9e 9e ................
00000040 9e f1 f1 f1 fa fa fa ea  ea ea ad ad ad a4 a4 a4 ................
00000050 d0 d0 d0 f6 f6 f6 e5 e5  e5 bc bc bc c3 c3 c3 97 ................
00000060 97 97 b4 b4 b4 d8 d8 d8  bf bf bf cb cb cb db db ................
00000070 db e1 e1 e1 93 93 93 7f  7f 7f 8d 8d 8d 85 85 85 .............
00000080 79 79 79 70 70 70 d9 a6  b1 29 00 00 08 fa 49 44 yyyppp...)....ID
00000090 41 54 78 9c e5 9d 89 92  a3 2a 14 40 45 45 09 a8 ATx......*.@EE..
000000a0 80 18 34 d3 3d ef ff 3f  f3 69 92 4e 67 71 45 90 ..4.=..?.i.NgqE.
000000b0 65 4e 55 4f a5 7b 52 c6  20 dc 9d 4b 14 f9 46 f7 eNUO.{R. ..K..F.
000000c0 87 36 79 8d 6d df 86 75  28 03 e4 4f c4 cb 28 ca .6y.m..u(..O..(.
000000d0 63 db f7 62 97 36 91 8f  e9 80 72 ce 6c de 8b 65 c..b.6....r.l..e
000000e0 c8 f9 f9 b7 14 53 68 eb  4e ac 73 a1 ef 7f 91 d2 .....Sh.N.s....
000000f0 c6 7d 6c 04 71 91 e9 be  66 f2 31 14 51 04 dd 97 .}l.q...f.1.Q...
00000100 a0 9c d0 8e e8 be 66 33  f6 d7 5a f3 a7 68 a7 e4 ......f3..Z..h..
00000110 91 f6 f9 8b c1 e8 9f 45  aa f5 53 34 93 45 71 7e .......E..S4.Eq~
00000120 7d 21 4a 9d 97 9d 98 00  ba 67 9f 4e b2 3a 61 a2 }!J......g.N.:a.
00000130 bb bd 96 10 f5 ff e2 b2  c3 d5 ee eb b6 13 b3 4c ...............L
00000140 a0 dd 97 36 06 96 51 c7  7f 7e 41 02 00 c8 da 86 ...6..Q.~A.....
00000150 13 00 bb 7d d7 9d 94 0b  f9 88 44 75 03 fc f5 f6 ...}......Du....
00000160 9c d2 d3 fd 45 d2 ff 34  cf 0f 17 89 75 aa 26 46 ....E..4....u.&F
00000170 b4 2d b9 98 fc 7f a0 75  29 ea 43 4e df b2 68 a2 .-....u).CN..h.
...
The binnary output of sec.png file:
[mythcat@desk test]$ python3 hex.py -b FILE sec.png 
00000000 10001001 01010000 01001110 01000111 00001101 00001010 00011010 00001010  
00000000 00000000 00000000 00001101 01001001 01001000 01000100 01010010 .PNG........IHDR
00000010 00000000 00000000 00000001 00001011 00000000 00000000 00000000 10111101
  00001000 00000011 00000000 00000000 00000000 10010011 01101111 10101000 ..............o.
00000020 10111100 00000000 00000000 00000000 01011101 01010000 01001100 01010100
  01000101 11111111 11111111 11111111 10101011 10101011 10101011 11111100 ....]PLTE.......
00000030 11111100 11111100 10100000 10100000 10100000 11110101 11110101 11110101
  10100110 10100110 10100110 11111001 11111001 11111001 10011110 10011110 ................
00000040 10011110 11110001 11110001 11110001 11111010 11111010 11111010 11101010
  11101010 11101010 10101101 10101101 10101101 10100100 10100100 10100100 ................
00000050 11010000 11010000 11010000 11110110 11110110 11110110 11100101 11100101
  11100101 10111100 10111100 10111100 11000011 11000011 11000011 10010111 ................
00000060 10010111 10010111 10110100 10110100 10110100 11011000 11011000 11011000
  10111111 10111111 10111111 11001011 11001011 11001011 11011011 11011011 ................
00000070 11011011 11100001 11100001 11100001 10010011 10010011 10010011 01111111
  01111111 01111111 10001101 10001101 10001101 10000101 10000101 10000101 .............
00000080 01111001 01111001 01111001 01110000 01110000 01110000 11011001 10100110
  10110001 00101001 00000000 00000000 00001000 11111010 01001001 01000100 yyyppp...)....ID
00000090 01000001 01010100 01111000 10011100 11100101 10011101 10001001 10010010
  10100011 00101010 00010100 01000000 01000101 01000101 00001001 10101000 ATx......*.@EE..
...

Wednesday, September 25, 2019

Python 3.7.4 : Print with random colors.

This is a simple example for custom print output.
The script detect the platform for color settings and then use print.
The first print will print with blue color the name of the script.
I used random to select a random color from colors array and used to print the -=RANDOM COLOR=- text.
The print (W+'') is used to set default white color for terminal
import sys
import random
if sys.platform == "linux" or sys.platform == "linux2":
        BB = "\033[34;1m" # Blue light
        YY = "\033[33;1m" # Yellow light
        GG = "\033[32;1m" # Green light
        WW = "\033[0;1m"  # White light
        RR = "\033[31;1m" # Red light
        CC = "\033[36;1m" # Cyan light
        B = "\033[34m"    # Blue
        Y = "\033[33m"    # Yellow
        G = "\033[32m"    # Green
        W = "\033[0m"     # White
        R = "\033[31m"    # Red
        C = "\033[36m"    # Cyan
colors = [BB,YY,GG,WW,RR,CC,B,Y,G,W,R,C]
print (B+"\033[2;2m "+sys.argv[0]+"\n"+B)

color=random.choice(colors)
print (color+"-=RANDOM COLOR=-"+color)
print (W+'')
For winodws platform you need to add this:
elif sys.platform == "win32":

 BB = '' # Blue light
 YY = '' # Yellow light
 GG = '' # Green light
 WW = '' # White light
 RR = '' # Red light
 CC = '' # Cyan light
 B = ''  # Blue
 Y = ''  # Yellow
 G = ''  # Green
 W = ''  # White
 R = ''  # Red
 C = ''  # Cyan
 P = ''  # Random color

Tuesday, October 10, 2017

The online editor for python and google .

This is a good online editor for python and google.
Like any online editor, some python modules are not available for online security reasons.
I do not know what python modules are implemented in this online editor.
I tested just sys and math python modules.
The Google Apps come with this tool integration like application for Google drive:
Edit your python file directly in your browser:
- Save it to Google Drive integrated with Google Drive
- Test it in your browser with Skulpt
- Use autocompletion code (CTRL+SPACE)
- No registration required and totally free
- Export your file
- Work offline
New python libraries partially supported: numpy, matplotlib.

Monday, February 10, 2014

My first logger python script to record keys .

Few days ago I worked with one issue : keyboard logger .
My first dilemma was: to use assemblly language or something simple like python.
My option was python - simple and fast to test how to deal with this issue.
About logger : A keyboard Logger is intended to record the keystrokes that a user inputs on a computer keyboard in addition to other user actions.
I make simple script after I search about how to deal with this.
You can see my script is simple and can be use if you want to record Python Interactive Interpreter.
I don't finish it , some keys like : backspace or enter will be put into log file.
So if you deal very well with python don't use this keys...
Anyway if I want to finish this then I need to fix this ...
Let's see the python script:
try:
 import pythoncom, pyHook, sys, logging
except:
 sys.exit()

#specials = {8:'BACKSPACE',9:'TAB',13:'ENTER', 27:'ESC', 32:'SPACE'}

specials = {9:'TAB',13:'ENTER', 27:'ESC'}
buffer = ''

def OnKeyboardEvent(event):
 try:
  logging.basicConfig(filename='C:\\aa\\log_output.txt',level=logging.DEBUG,format='%(message)s')
  global buffer
  
  if event.Ascii in range(32,127):
   print chr(event.Ascii)
   buffer += chr(event.Ascii)
  
  if event.Ascii in specials:
   print '<'+specials[event.Ascii]+'>'
   logging.log(10,buffer)
   buffer = ''
   logging.log(10,'<'+specials[event.Ascii]+'>')
   
  return True
 except:
  sys.exit()

hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
Let's see the result of this :

The output log text file ...:
python 
<ENTER>
import os 
<ENTER>
import sys
<ENTER>


Thursday, June 13, 2013

What you need : stdout or print ?

My question is much more complicated than intended and I will show you in this tutorial.

Most users use print or print() - if it used in python 3.

For example you can use this without import any python module.

$ python 
Python 2.6.8 (unknown, Apr 14 2013, 18:10:41) 
[GCC 4.3.2 20081105 (Red Hat 4.3.2-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "my text"
my text
>>> 

This is simple to show some strings.

What the most people don't know about print function it's the interface of stdout.write.

Let's see another example with stdout.write .

>>> sys.stdout.write(str(my text) + '\n')   
  File "<stdin>", line 1
    sys.stdout.write(str(my text) + '\n')
                               ^
SyntaxError: invalid syntax
>>> sys.stdout.write(str("my text") + '\n')                  
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sys' is not defined

First error tells us about function str.It's need just one arg not this my text.

The next error tells us about sys module is not import by python.

Note: This restriction can help us sometime.

Some example using stdout.write :

First is : my text example , see I add '\n' to go to the next row.

>>> import sys 
>>> sys.stdout.write("my text"+'\n')
my text

Let's try to change the output.

See the next image :

You can say : I can do this with print function.

>>> print "\033[0;32m"+"my text"+"\033[0m"
my text

Yes! Right. Can you do this ? (see the next video)


Saturday, May 22, 2010

The beauty of Python: Some examples with os and sys modules - part 2

Today i will tell about sys and os modules.
The module os has OS routines for Mac, NT, or Posix depending on what system we're on.
The module sys provides access to some objects used or maintained by the interpreter and to functions that interact strongly with the interpreter.

Some useful functions with sys module.
>>> print sys.version
2.5.2 (r252:60911, Oct  5 2008, 19:24:49) 
[GCC 4.3.2]
>>> print sys.version_info
(2, 5, 2, 'final', 0)
>>> print sys.subversion
('CPython', 'tags/r252', '60911')
>>> print sys.platform 
linux2
>>> print sys.ps1
>>> 
>>> print sys.ps2
... 
>>> print sys.prefix
/usr
>>> print sys.path
['', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk',
'/usr/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages',
 '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/Numeric',
'/usr/lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/site-packages/gst-0.10',
 '/var/lib/python-support/python2.5', '/usr/lib/python2.5/site-packages/gtk-2.0', 
'/var/lib/python-support/python2.5/gtk-2.0']
>>> print sys.modules.keys()
['apt.os', 'email.iterators', 'apport.sys', 'random', 'apport.atexit', 'subprocess',
 'email.MIMEImage', 'gc', 'apport.pwd', 'os.path', 'encodings.encodings', 'email.mime',
 'email.MIMEText', 'xml', 'email.time', 'struct', 'tempfile', 'base64', 'apt.cache',
 'pyexpat.errors', 'apt_pkg', 'apport', 'email.binascii', 'email.Parser', 'zipimport',
 'apport.xml', 'xml.dom.copy', 'encodings.utf_8', 'apt.apt_pkg', 'email.quoprimime',
 'email.mime.text', 'email.urllib', 'email.FeedParser', 'signal', 'email.encoders',
 'pyexpat.model', 'apport.packaging_impl', 'apport.cStringIO', 'quopri',
 'email.Message', 'cStringIO', 'zlib', 'locale', 'email.charset', 'apport.fileutils',
 'xml.parsers.expat', 'atexit', 'email.quopriMIME', 'encodings', 'email.Generator',
 'apport.warnings', 'apport.problem_report', 'apt.fcntl', 'email.MIMEAudio', 'urllib',
 're', 'apt.select', 'email.quopri', 'apport.report', 'email.mime.base', 'email.errors',
 'email', 'math', 'fcntl', 'apport.os', 'apt.progress', 'UserDict', 'exceptions',
 'apport.grp', 'apport.shutil', 'codecs', 'xml.dom.domreg', 'email.Header', '_locale',
 'email.Iterators', 'socket', 'thread', 'traceback', 'apt.apt', 'e,
 'SUDO_COMMAND': '/bin/su', 'SUDO_GID': '999', 'SDL_VIDEO_CENTERED': '1',
 'PWD': '/home/mint/Desktop', 'COLORTERM': 'gnome-terminal', 'MAIL': '/var/mail/root'}
mail.Charset', 'xml.dom.xmlbuilder', 'os', 'marshal', 'apport.stat', 'apport.re',
 'apt.gettext', 'email.uu', '_sre', 'unittest', '__builtin__', 'apport.apport',
 'xml.parsers', 'apport.fnmatch', 'apport.urllib', 'operator', 'xml.parsers.pyexpat',
 'email.Errors', 'select', 'apt.string', 'apport.glob', 'apt.warnings', 'email.socket',
 'posixpath', 'email.base64MIME', 'errno', '_socket', 'binascii', 'email.Utils',
 'sre_constants', 'email.MIMEMessage', 'email._parseaddr', 'email.sys',
 'apport.traceback', 'apt.package', 'apt.random', 'xml.dom.NodeFilter',
 'email.MIMENonMultipart', '_codecs', 'apport.unittest', 'apport.apt', 'email.os',
 'email.utils', 'pwd', 'apport.time', 'copy', '_struct', '_types', 'email.email',
 'apt.cdrom', 'uu', 'xml.dom.minidom', 'apport_python_hook', 'apt', 'email.random',
 'posix', 'encodings.aliases', 'apt.sys', 'fnmatch', 'sre_parse', 'pickle', 'copy_reg',
 'sre_compile', '_random', 'site', 'email.base64', 'apt.errno', '__main__', 'problem_report',
 'pyexpat', 'email.MIMEBase', 'email.message', 'string', 'email.mime.nonmultipart',
 'apport.subprocess', 'shutil', 'strop', 'grp', 'encodings.codecs', 'gettext',
 'email.warnings', 'xml.dom.minicompat', 'email.MIMEMultipart', 'types', 'apport.tempfile',
 'stat', '_ssl', 'warnings', 'encodings.types', 'glob', 'email.re', 'sys', 'email.Encoders',
 'readline', 'email.cStringIO', 'xml.dom', 'xml.dom.xml', 'apport.signal', 'sitecustomize',
 'email.mime.email', 'email.base64mime', 'email.mime.multipart', 'apport.packaging',
 'urlparse', 'linecache', 'email.string', 'apt.re', 'time', 'gzip']


And now, some useful functions with os module.
>>> print os.uname()
('Linux', 'mint', '2.6.27-7-generic', '#1 SMP Fri Oct 24 06:42:44 UTC 2008', 'i686')
>>> print os.ttyname(1)
/dev/pts/0
>>> print os.times()
(0.050000000000000003, 0.02, 0.0, 0.0, 17186002.649999999)
>>> print os.environ
{'USERNAME': 'root', 'LANG': 'en_US.UTF-8', 'TERM': 'xterm', 'SHELL': '/bin/bash',
 'XDG_SESSION_COOKIE': '842d38513df1a6bb7490c8a14bf69489-1274456064.963733-1686354756',
 'SUDO_COMMAND': '/bin/su', 'SHLVL': '1', 'RUNNING_UNDER_GDM': 'yes', 'SUDO_UID': '999',
 'SUDO_GID': '999', 'PWD': '/home/mint/Desktop', 'LOGNAME': 'root', 'USER': 'root',
 'COLORTERM': 'gnome-terminal',
 'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games',
 'MAIL': '/var/mail/root', 'SUDO_USER': 'mint', 'HOME': '/root', 'DISPLAY': ':0.0',
 '_': '/usr/bin/python', 'XAUTHORITY': '/home/mint/.Xauthority'}
>>> print os.mkdir('aaa')
None
>>> print os.mkdir('aaa')
Traceback (most recent call last):
File "", line 1, in 
OSError: [Errno 17] File exists: 'aaa'
>>> print os.listdir('/')
['media', 'root', 'sbin', 'usr', 'lib', 'tmp', 'home', 'var', 'cdrom', 'etc',
 'rofs', 'bin', 'boot', 'dev', 'initrd.img', 'mnt', 'opt', 'proc', 'srv',
 'sys', 'vmlinuz']

These is just a brief tutorial about sys and os modules.