Friday, August 3, 2018

Python OS functions explained






The OS module in python is very useful for testing the functionality of underlying operating system like linux,Mac,windows etc

before applying these modules we need to import the os module using the command  import os

The main os functions are given below

os.system ()- this is for executing shell command 


ex: os.system ("rpm --ivh aide*")  - this will install the aide rpm in the system 



os.stat () - This command will give the status of a file 


ex: print "getting the status of: ", os.stat('/usr/bin/python')

getting the status of:  posix.stat_result(st_mode=33261, st_ino=1051053, st_dev=2054, st_nlink=1, st_uid=0, st_gid=0, st_size=3542008, st_atime=1532933669, st_mtime=1511456897, st_ctime=1519176316)



os.environ() - Get the users environment


ex: 

import os

ux = os.environ['HOME']
print ux

out:/home/unixchips


os.chdir() # Move focus to a different directory

ex:

import os

print os.chdir('/home/unixchips/Desktop')

print (os.getcwd())

output: /home/unixchips/Desktop

os.getgid() # Return the real group id of the current process

ex:

import os

print os.getgid()

output:1000

os.getuid() # Return the current process’s user id

ex:

import os

print os.getuid()

output: 1000

os.getpid() # Returns the real process ID of the current process

ex:

import os

print os.getpid()

output:18616

getpass.getuser()# Return the name of the user logged

ex:

import getpass

print (getpass.getuser())

output:unixchips


os.access() # Check file status 

ex:

import os
path = '/tmp/test.txt'
print os.access(path, os.R_OK)

output:True

os.chmod() # Change the mode of path to the numeric mode

in this case you need to import a module called stat along with OS which will act a parameter , below are the parameter's used to change the ownership of a file 




stat.S_ISUID − Set user ID on execution.


stat.S_ISGID − Set group ID on execution.


stat.S_ENFMT − Record locking enforced.


stat.S_ISVTX − Save text image after execution.


stat.S_IREAD − Read by owner.


stat.S_IWRITE − Write by owner.


stat.S_IEXEC − Execute by owner.


stat.S_IRWXU − Read, write, and execute by owner.


stat.S_IRUSR − Read by owner.


stat.S_IWUSR − Write by owner.


stat.S_IXUSR − Execute by owner.


stat.S_IRWXG − Read, write, and execute by group.


stat.S_IRGRP − Read by group.


stat.S_IWGRP − Write by group.


stat.S_IXGRP − Execute by group.


stat.S_IRWXO − Read, write, and execute by others.


stat.S_IROTH − Read by others.


stat.S_IWOTH − Write by others.


stat.S_IXOTH − Execute by others.


ex:

import os, stat

os.chmod('/tmp/test.txt',stat.S_IRWXU)

(this will provide executable permission to the /tmp/test.txt by the owner )

output: -rwx------ 1 unixchips unixchips    0 Jul 31 23:39 test.txt


os.chown() # Change the owner and group id

(you need to perform this as a root user only)

ex:

import os, sys

os.chown("/tmp/test.txt", 1001, 1001)

output: -rwx------ 1 ratheesh  ratheesh     0 Jul 31 23:39 test.txt


os.umask(mask) # Set the current numeric umask


import os


os.umask(0777)
open("/tmp/sample.txt", "w").close()

output:                ---------- 1 root      root         0 Aug  1 21:04 sample.txt



os.getsize() # Get the size of a file


import os


print os.path.getsize("/tmp/test.txt")

output: 20 (as it is a 20B file)



os.environ() # Get the users environment

suppose if we want to get the home directory of current user root below program can be used 

ex:


import os

print os.environ.get('HOME')

output:root

to get all the environment variables of a user below program 


import os

for param in os.environ.keys():

    print "%20s %s" % (param,os.environ[param])

output
*******************************************************************************
/root
root@unixchips:~# nano env.py
root@unixchips:~# nano env1.py
root@unixchips:~# python env1.py 
                LANG en_IN
                TERM xterm-256color
               SHELL /bin/bash
           LESSCLOSE /usr/bin/lesspipe %s %s
          XAUTHORITY /home/unixchips/.Xauthority
            LANGUAGE en_IN:en
               SHLVL 1
QT_QPA_PLATFORMTHEME appmenu-qt5
            LESSOPEN | /usr/bin/lesspipe %s
                 PWD /root
             LOGNAME root
                USER root
                PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin
                MAIL /var/mail/root
           LS_COLORS rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:
                HOME /root
             DISPLAY :0
                   _ /usr/bin/python
********************************************************************************


os.uname() # Return information about the current operating system

ex:
import os

print os.uname()

output:   ('Linux', 'unixchips', '4.15.0-24-generic', '#26~16.04.1-Ubuntu SMP Fri Jun 15 14:35:08 UTC 2018', 'x86_64')


os.chroot(path) # Change the root directory of the current process to path & os.getcwd

ex:
import os, sys

os.chdir("/tmp")
print os.getcwd()

output: /tmp

os.chroot(path) # Change the root directory of the current process to path

ex:

import os

print os.listdir('/tmp')

output: (will display the contents of the /tmp directory)

['.XIM-unix', 'systemd-private-5ccc0291bc60473d8d8fc248cff92fd3-systemd-timesyncd.service-OnYY3G', 'gnome-software-D9QEMZ', 'gnome-software-E1KUMZ', 'Temp-8984a84e-9508-434e-8180-a9cfbaa969c8', '.font-unix', 'gnome-software-VTVXMZ', 'gnome-software-N6ZDMZ', 'sample.txt', 'test.txt', '.wine-1000', '.Test-unix', 'gnome-software-3RD9MZ', '.org.chromium.Chromium.KfRkcm', 'systemd-private-5ccc0291bc60473d8d8fc248cff92fd3-rtkit-daemon.service-wVPLTC', 'unity_support_test.0', '.X0-lock', 'gnome-software-UMBENZ', 'gnome-software-IY0GNZ', 'gnome-software-4GZUMZ', '.ICE-unix', 'systemd-private-5ccc0291bc60473d8d8fc248cff92fd3-colord.service-BSHI7z', '.X11-unix', 'config-err-SiAh3i', 'gnome-software-3657MZ', '.org.chromium.Chromium.dI8BqE', 'gnome-software-SSMSMZ', 'gnome-software-XX9GMZ']


os.getloadavg() # Show queue averaged over the last 1, 5, and 15 minutes

ex:
import os

print os.getloadavg()

output: (which will display load average of  1,5,15 minutes)
(0.75, 0.69, 0.59) 


os.path.exists()# Check if a path exists

ex:

import os

print os.path.exists('/tmp/test.txt')

output: true


os.walk() # Print out all directories, sub-directories and files

The syntax of the os.walk will be 

os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])

  • top − Each directory rooted at directory, yields 3-tuples, i.e., (dirpath, dirnames, filenames)
  • topdown − If optional argument topdown is True or not specified, directories are scanned from top-down. If topdown is set to False, directories are scanned from bottom-up.
  • onerror − This can show error to continue with the walk, or raise the exception to abort the walk.
  • followlinks − This visits directories pointed to by symlinks, if set to true.

ex:


import os
for root, dirs, files in os.walk("/tmp", topdown=False):
   for name in files:
      print(os.path.join(root, name))
   for name in dirs:
      print(os.path.join(root, name))


output: ( List all directories /subdrectories  and files 


/tmp/systemd-private-5ccc0291bc60473d8d8fc248cff92fd3-systemd-timesyncd.service-OnYY3G/tmp
/tmp/gnome-software-D9QEMZ/debconf.socket
/tmp/gnome-software-E1KUMZ/debconf.socket
/tmp/gnome-software-VTVXMZ/debconf.socket
/tmp/gnome-software-N6ZDMZ/debconf.socket
/tmp/.wine-1000/server-806-3e0902/lock
/tmp/.wine-1000/server-806-3e0902
/tmp/gnome-software-3RD9MZ/debconf.socket
/tmp/.org.chromium.Chromium.KfRkcm/SingletonCookie
/tmp/.org.chromium.Chromium.KfRkcm/SingletonSocket
/tmp/systemd-private-5ccc0291bc60473d8d8fc248cff92fd3-rtkit-daemon.service-wVPLTC/tmp
/tmp/gnome-software-UMBENZ/debconf.socket
/tmp/gnome-software-IY0GNZ/debconf.socket
/tmp/gnome-software-4GZUMZ/debconf.socket
/tmp/.ICE-unix/2087
/tmp/systemd-private-5ccc0291bc60473d8d8fc248cff92fd3-colord.service-BSHI7z/tmp
/tmp/.X11-unix/X0
/tmp/gnome-software-3657MZ/debconf.socket
................................................

os.mkdir(path) # Create a directory named path with numeric mode mode

ex: 
import os 

os.mkdir('/tmp/ratheesh')

output: 
drwxr-xr-x 2 root root 4096 Aug  3 14:09 /tmp/ratheesh/


os.rmdir(path) # Remove (delete) the directory path


ex:
import os

os.rmdir('/tmp/ratheesh')

output:
root@unixchips:~# ls ld /tmp/ratheesh
ls: cannot access 'ld': No such file or directory
ls: cannot access '/tmp/ratheesh': No such file or directory


os.rename(src, dst) # Rename the file or directory src to dst

ex:
import os

os.rename('/tmp/test.txt', '/tmp/test1.txt')

output:
-rwx------ 1 ratheesh ratheesh 20 Aug  1 21:11 /tmp/test1.txt






























No comments:

Post a Comment