OS Module in Python (Python Part 14)

This class shows you how to use the OS Module to interact with the operating system and gain access to applications and tools that reside on the OS.

  • 00:00 Intro
  • 05:01 Warning
  • 13:17 os.system function
  • 20:40 os.popen
  • 27:36 os.path
  • 35:58 os System Functions
  • 44:09 Demo – Looping Network Monitor with Ping
  • 54:39 Final Thoughts

os-system.py

import os

command = 'touch os-test.txt'

os.system(command)

#result = os.system(command)

#print(result)

os-popen.py

import os

host = input('Host / IP Address to ping: ')
command = (f'ping -c 1 {host}')
response = os.popen(command).read()

print(response)

os-directory.py

import os

directory = os.path.dirname(os.path.abspath(__file__))

print(directory)

file_name = 'os-test.txt'

file_path = os.path.join(directory, file_name)

with open(file_path, 'w') as file:
    file.write('The OS Module is COOL')

with open(file_path, 'r') as file:
    message = file.read()

print(message)

os-basic-functions.py

import os

os.mkdir('test-dir')

#os.rename('test-dir', 'not-test-dir')

#os.rmdir('not-test-dir')

result = os.scandir()

for x in result:
    print(x)

os-demo.py

import os
import time

sites = input('Hosts and IP Addresses to Test: ')

sites = sites.split(' ')

#print(sites)

while True:
    os.system('clear')
    for address in sites:
        try:
            command = (f'ping -c 1 {address}')
            #response = os.popen(command).read()
            response = os.popen(f'{command} 2> /dev/null').read()
            #print(response)
            if '1 packets received' in response:
                print(f'{address} is UP')
            else:
                print(f'{address} is DOWN')
        except:
            print(f'{address} COMMAND FAILED')
        
    time.sleep(5)

Be the first to comment

Leave a Reply