Concept: Platform Identification Examples

Total Page:16

File Type:pdf, Size:1020Kb

Concept: Platform Identification Examples Unit III - focuses on using Python to develop sustainable code. In this unit students will be working with Python Modules, More Powerful Statements, Methods and Structures for Robust Code, and Proper Functions. Students will be introduced to data structures and files in Python 3 and be ready for more-advanced Python learning. Module I – Python Modules File System Students will be able to: • sys.platform • Identify the platform running a • os: os.getcwd, os.chdir, os.listdir, Python script ('Linux', 'win32', os.mkdir, os.rmdir, os.rename 'Darwin') • os.path: os.path.abspath, • Get the current working directory os.path.exists, os.path.isfile, • Change the current working directory os.path.isdir • List the content of the current working directory • Create a new directory • Remove a directory • Rename files and directories • Recognize the difference between relative and absolute paths • Test whether a path exists • Test whether a specific file or directory exists Activity 4 – File System 1. Open Your IDE of Choice (Notebooks.Azzure, repl.It or Visual Studio) 2. Open a New Project 3. Name it U3_M1_A4-XX (XX represents your first initial and last name I.E Mjordan). 4. Insert your program comments. 5. Insert a line comment to identify each step. Concept: Platform Identification 6. View this video – Using the sys module In recent years, when you reach the download page of a website, you are directed to download a file that matches your operating system. For example, when using a Windows computer, download links direct you to .exe files; similarly, when using a Mac, you download links direct you to .dmg files. This code awareness makes the user experience more pleasant. Python scripts can run on different platforms, including Windows, Mac, and Linux. The sys module provides access to several system variables, including the platform. If you know the platform your Python code is running on, you may be able to change the behavior of your application to accommodate that platform. Examples Identifying the platform 7. import sys print(sys.platform) Concept: Directory Operations 8. View This Video – Directory Operations Most operating systems organize files in hierarchical structures. For example, directories (also known as folders) may contain other directories and files. The Python os module contains some useful functions to navigate and manipulate files and directories. In the following sections, you will see how to perform some basic directory operations. Finding and changing the current working directory When navigating the hierarchical file system, you will always be located in a directory. The directory you're in is referred to as the "current working directory", or "cwd" for short. Python's os.getcwd() nethod returns a string containing the current working directory path. The working directory can be changed in Python using os.chdir(path), which changes the cwd into path, which is a string variable containing a path to the new working directory. NOTE: When changing a working directory, you can specify .. as your path. This effectively changes the working directory one level up into the parent directory. Listing the content of a directory You might need to access or read the content of a directory. The os.listdir() method returns a list of the files and directories in the current working directory. Creating and removing directories In Python, a new directory can be created manually using os.mkdir(path), where path is the path and name of the new directory. Similarly, a directory can be removed using os.rmdir(path), where path is the name of the directory to be deleted. Note that rmdir can delete only empty directories; if the directory specified by path is not empty, an error will be raised. Renaming files and directories Many tasks can be automated by Python. For example, if you want to rename a large number of files to match a predefined pattern, you can use Python's os.rename(src, dst) method, in which src is a string containing the path of a source file or directory, and dst is a string containing the new (destination) path and/or name. Examples Directory structure The examples in this lesson traverse through the following directory structure. parent_dir |__ child1_dir | | | |_ leaf1.txt | |__ child2_dir | | | |_ leaf2.txt | |__ parent_leaf.txt | |__ text_file.txt Directories The directories in this structure are parent_dir, child1_dir, and child2_dir. Files The files in this structure are leaf1.txt, leaf2.txt, parent_leaf.txt, and text_file.txt. Working directory In this example, you will change the current working directory to parent_dir, then to child1_dir, then back to parent_dir. You will also see a printout of the current working directory at every step. 9. import os # Change the current working directory to parent dir os.chdir('parent_dir') print('Changed working dir to parent: ', os.getcwd()) # Change the current working directory to child1 dir os.chdir('child1_dir') print('Changed working dir to child1: ', os.getcwd()) # Change the current working directory back to the parent dir os.chdir('..') print('Changed working dir back to parent: ', os.getcwd()) Directory content In this example, you will list the content of the current working directory (parent_dir). 10. import os # Print the current working directory (should be "parent_dir") print('The current working directory is:', os.getcwd()) # List the content of the directory (both files and other directories) print('Current directory content: ', os.listdir()) Creating and removing directories In this example, you will create and remove directories. 11. import os # Print the current working directory (should be "parent_dir") print('The current working directory is:', os.getcwd()) # Create a new directory os.mkdir('new_child') print('Created new_child dir') # List the content of the directory print('Current directory content: ', os.listdir()) # Remove the new child directory os.rmdir('new_child') print('Removed new_child dir') # List the content of the directory print('Current directory content: ', os.listdir()) Renaming directories In this example, you will create a new directory, and then change its name. 12. import os # Print the current working directory (should be "parent_dir") print('The current working directory is:', os.getcwd()) # Create a new directory os.mkdir('new_child') print('Created new_child dir') # List the content of the directory print('Current directory content:', os.listdir()) # Rename new_child as old_child os.rename('new_child', 'old_child') print('Renamed new_child as old_child') # List the content of the dir print('Current directory content: ', os.listdir()) # Remove the old_child dir os.rmdir('old_child') print('Removed old_child dir') print('Current directory content: ', os.listdir()) Task 1: Directory Operations 13. Write a program to: • Prompt the user for a directory name • Create the directory • Verify the directory was created by listing the content of the current working directory • Remove the created directory • Verify the directory was removed by listing the contents of the current working directory • Import os • Create a variable dirName = and ask for user input to enter a directory name • Print dirName • Use mkdir to os and include dirName • Print a complete sentence stating the current directory content, using .listdir() on os • Print a complete sentence stating removal of dirName using rmdir() on os • Print a complete sentence stating the current directory content, using .listdir() on os 14. Write a program to: • Create a directory called "myDir" • Change the current working directory to "myDir" • Verify you are in the correct directory by displaying the current working directory • Change the working directory back to the parent directory • Verify you are in the correct directory by displaying the current working directory • Rename "myDir" to "yourDir" • Verify the directory was renamed by listing the content of the current working directory • Remove "yourDir" • Verify the directory was removed by listing the content of the current working directory • Import os • Write a statement stating you are making myDir • Use mkdir() on os to make “myDir) • Print a statement to notify changing working directory • Use .chdir to change working directory to myDir • Display the current working directory • Use a print statement to state the current working directory • Use .getcwd() • Print a statement to notify changing working directory • Use chdir() to get back to parent directory • Display the current working directory • Use a print statement to state the current working directory • Use .getcwd() • Print a statement notifying change of myDir to yourDir • Use .rename() to rename myDir • Use a print statement to verify current directory content • Use .listdir() • Write a print statement to remove yourDir • Use rmdir() to remove yourDir • Use a print statement to verify current directory content • Use .listdir() Concept: Path Operations 15. View This Video – Path Operations Relative and absolute paths A file or directory has a name and a path, which is just a roadmap to its specific location in the file system. Most operating systems, support two types of paths: • Relative paths: path to a file or directory from a specific location (or current working directory) • Absolute paths: path to a file or directory from a root. In UNIX flavors, a root is "/"; whereas, on Windows machines a root is "C:\" For example, consider the UNIX directory structure we have been manipulating: / | |__ parent_dir | |__ child1_dir | | | |_ leaf1.txt | |__ child2_dir | | | |_ leaf2.txt | |__ parent_leaf.txt | |__ text_file.txt If you are currently in parent_dir and trying to get to leaf1.txt, the relative path would be (child1_dir/leaf1.txt). It's a relative path because it is relative to your current location. The absolute path to leaf1.txt is (/parent_dir/child1_dir/leaf1.txt), it starts from the root "/" all the way to the destination file. It's absolute because it starts from the absolute root. In Python, you can use relative or absolute paths; however, it might be useful to convert a relative path into an absolute path using the function os.path.abspath(path).
Recommended publications
  • 7843 Directory Management
    7843 Directory Management Tired of using existing badly written operating systems, Hieu decided to write his new one. Of course, his new operating system will be awesome, bug-free, fast and easy to use. He has finished most of the work, and now he is asking you to do one lasttask: Implement a directory manager. Initially, Hieu’s computer directory is empty. The current directory is the root directory. The directory manager keeps the directory in a rooted-tree structure. In each directory, the children are sorted in lexicographical order. He can do one of the following actions: • MKDIR s: create a child directory named s inside the current directory where s is a string. – If the current directory already contains a child directory named s, print “ERR” and do nothing. – Otherwise, print “OK” • RM s: remove a child directory named s inside the current directory where s is a string. Figure 1 – If there is no child directory named s, print “ERR”. Otherwise, print “OK”. • CD s: change the current directory to a child directory named s where s is a string. – If s is equal to the string “..” and the current directory is the root directory, print “ERR” and do nothing. – If s is equal to the string “..” and the current directory is not the root direc- tory, then you need to change the current directory to the parent directory Figure 2 and print “OK”. – If there is no child directory named s, print “ERR” and do nothing. – If there is a child directory named s then you need to change the current directory to s and print “OK”.
    [Show full text]
  • Print Wizard 3 Manual
    Print Wizard User Guide and Technical Manual Version 3.0 and later Rasmussen Software, Inc. 10240 SW Nimbus Ave., Suite L9, Portland, Oregon 97223 (503) 624-0360 www.anzio.com [email protected] Copyright © 2004-2005 by Rasmussen Software, Inc., All Rights Reserved Rasmussen Software, Inc. Page 1 Print Wizard Manual Table of Contents Table of Contents PRINT WIZARD USER GUIDE.......................................................................................................................................... 7 1 PRINT WIZARD INTRODUCTION ......................................................................................................................................... 7 1.1 What is Print Wizard?............................................................................................................................................... 7 1.2 Concept..................................................................................................................................................................... 7 1.3 Profiles and Services .............................................................................................................................................. 10 1.3.1 Introduction to print profiles................................................................................................................................................11 1.3.2 Introduction to services .......................................................................................................................................................12
    [Show full text]
  • Disk Clone Industrial
    Disk Clone Industrial USER MANUAL Ver. 1.0.0 Updated: 9 June 2020 | Contents | ii Contents Legal Statement............................................................................... 4 Introduction......................................................................................4 Cloning Data.................................................................................................................................... 4 Erasing Confidential Data..................................................................................................................5 Disk Clone Overview.......................................................................6 System Requirements....................................................................................................................... 7 Software Licensing........................................................................................................................... 7 Software Updates............................................................................................................................. 8 Getting Started.................................................................................9 Disk Clone Installation and Distribution.......................................................................................... 12 Launching and initial Configuration..................................................................................................12 Navigating Disk Clone.....................................................................................................................14
    [Show full text]
  • Command Line Interface Specification Windows
    Command Line Interface Specification Windows Online Backup Client version 4.3.x 1. Introduction The CloudBackup Command Line Interface (CLI for short) makes it possible to access the CloudBackup Client software from the command line. The following actions are implemented: backup, delete, dir en restore. These actions are described in more detail in the following paragraphs. For all actions applies that a successful action is indicated by means of exit code 0. In all other cases a status code of 1 will be used. 2. Configuration The command line client needs a configuration file. This configuration file may have the same layout as the configuration file for the full CloudBackup client. This configuration file is expected to reside in one of the following folders: CLI installation location or the settings folder in the CLI installation location. The name of the configuration file must be: Settings.xml. Example: if the CLI is installed in C:\Windows\MyBackup\, the configuration file may be in one of the two following locations: C:\Windows\MyBackup\Settings.xml C:\Windows\MyBackup\Settings\Settings.xml If both are present, the first form has precedence. Also the customer needs to edit the CloudBackup.Console.exe.config file which is located in the program file directory and edit the following line: 1 <add key="SettingsFolder" value="%settingsfilelocation%" /> After making these changes the customer can use the CLI instruction to make backups and restore data. 2.1 Configuration Error Handling If an error is found in the configuration file, the command line client will issue an error message describing which value or setting or option is causing the error and terminate with an exit value of 1.
    [Show full text]
  • Mac Keyboard Shortcuts Cut, Copy, Paste, and Other Common Shortcuts
    Mac keyboard shortcuts By pressing a combination of keys, you can do things that normally need a mouse, trackpad, or other input device. To use a keyboard shortcut, hold down one or more modifier keys while pressing the last key of the shortcut. For example, to use the shortcut Command-C (copy), hold down Command, press C, then release both keys. Mac menus and keyboards often use symbols for certain keys, including the modifier keys: Command ⌘ Option ⌥ Caps Lock ⇪ Shift ⇧ Control ⌃ Fn If you're using a keyboard made for Windows PCs, use the Alt key instead of Option, and the Windows logo key instead of Command. Some Mac keyboards and shortcuts use special keys in the top row, which include icons for volume, display brightness, and other functions. Press the icon key to perform that function, or combine it with the Fn key to use it as an F1, F2, F3, or other standard function key. To learn more shortcuts, check the menus of the app you're using. Every app can have its own shortcuts, and shortcuts that work in one app may not work in another. Cut, copy, paste, and other common shortcuts Shortcut Description Command-X Cut: Remove the selected item and copy it to the Clipboard. Command-C Copy the selected item to the Clipboard. This also works for files in the Finder. Command-V Paste the contents of the Clipboard into the current document or app. This also works for files in the Finder. Command-Z Undo the previous command. You can then press Command-Shift-Z to Redo, reversing the undo command.
    [Show full text]
  • Attacker Antics Illustrations of Ingenuity
    ATTACKER ANTICS ILLUSTRATIONS OF INGENUITY Bart Inglot and Vincent Wong FIRST CONFERENCE 2018 2 Bart Inglot ◆ Principal Consultant at Mandiant ◆ Incident Responder ◆ Rock Climber ◆ Globetrotter ▶ From Poland but live in Singapore ▶ Spent 1 year in Brazil and 8 years in the UK ▶ Learning French… poor effort! ◆ Twitter: @bartinglot ©2018 FireEye | Private & Confidential 3 Vincent Wong ◆ Principal Consultant at Mandiant ◆ Incident Responder ◆ Baby Sitter ◆ 3 years in Singapore ◆ Grew up in Australia ©2018 FireEye | Private & Confidential 4 Disclosure Statement “ Case studies and examples are drawn from our experiences and activities working for a variety of customers, and do not represent our work for any one customer or set of customers. In many cases, facts have been changed to obscure the identity of our customers and individuals associated with our customers. ” ©2018 FireEye | Private & Confidential 5 Today’s Tales 1. AV Server Gone Bad 2. Stealing Secrets From An Air-Gapped Network 3. A Backdoor That Uses DNS for C2 4. Hidden Comment That Can Haunt You 5. A Little Known Persistence Technique 6. Securing Corporate Email is Tricky 7. Hiding in Plain Sight 8. Rewriting Import Table 9. Dastardly Diabolical Evil (aka DDE) ©2018 FireEye | Private & Confidential 6 AV SERVER GONE BAD Cobalt Strike, PowerShell & McAfee ePO (1/9) 7 AV Server Gone Bad – Background ◆ Attackers used Cobalt Strike (along with other malware) ◆ Easily recognisable IOCs when recorded by Windows Event Logs ▶ Random service name – also seen with Metasploit ▶ Base64-encoded script, “%COMSPEC%” and “powershell.exe” ▶ Decoding the script yields additional PowerShell script with a base64-encoded GZIP stream that in turn contained a base64-encoded Cobalt Strike “Beacon” payload.
    [Show full text]
  • Powershell Integration with Vmware View 5.0
    PowerShell Integration with VMware® View™ 5.0 TECHNICAL WHITE PAPER PowerShell Integration with VMware View 5.0 Table of Contents Introduction . 3 VMware View. 3 Windows PowerShell . 3 Architecture . 4 Cmdlet dll. 4 Communication with Broker . 4 VMware View PowerCLI Integration . 5 VMware View PowerCLI Prerequisites . 5 Using VMware View PowerCLI . 5 VMware View PowerCLI cmdlets . 6 vSphere PowerCLI Integration . 7 Examples of VMware View PowerCLI and VMware vSphere PowerCLI Integration . 7 Passing VMs from Get-VM to VMware View PowerCLI cmdlets . 7 Registering a vCenter Server . .. 7 Using Other VMware vSphere Objects . 7 Advanced Usage . 7 Integrating VMware View PowerCLI into Your Own Scripts . 8 Scheduling PowerShell Scripts . 8 Workflow with VMware View PowerCLI and VMware vSphere PowerCLI . 9 Sample Scripts . 10 Add or Remove Datastores in Automatic Pools . 10 Add or Remove Virtual Machines . 11 Inventory Path Manipulation . 15 Poll Pool Usage . 16 Basic Troubleshooting . 18 About the Authors . 18 TECHNICAL WHITE PAPER / 2 PowerShell Integration with VMware View 5.0 Introduction VMware View VMware® View™ is a best-in-class enterprise desktop virtualization platform. VMware View separates the personal desktop environment from the physical system by moving desktops to a datacenter, where users can access them using a client-server computing model. VMware View delivers a rich set of features required for any enterprise deployment by providing a robust platform for hosting virtual desktops from VMware vSphere™. Windows PowerShell Windows PowerShell is Microsoft’s command line shell and scripting language. PowerShell is built on the Microsoft .NET Framework and helps in system administration. By providing full access to COM (Component Object Model) and WMI (Windows Management Instrumentation), PowerShell enables administrators to perform administrative tasks on both local and remote Windows systems.
    [Show full text]
  • Linux-PATH.Pdf
    http://www.linfo.org/path_env_var.html PATH Definition PATH is an environmental variable in Linux and other Unix-like operating systems that tells the shell which directories to search for executable files (i.e., ready-to-run programs ) in response to commands issued by a user. It increases both the convenience and the safety of such operating systems and is widely considered to be the single most important environmental variable. Environmental variables are a class of variables (i.e., items whose values can be changed) that tell the shell how to behave as the user works at the command line (i.e., in a text-only mode) or with shell scripts (i.e., short programs written in a shell programming language). A shell is a program that provides the traditional, text-only user interface for Unix-like operating systems; its primary function is to read commands that are typed in at the command line and then execute (i.e., run) them. PATH (which is written with all upper case letters) should not be confused with the term path (lower case letters). The latter is a file's or directory's address on a filesystem (i.e., the hierarchy of directories and files that is used to organize information stored on a computer ). A relative path is an address relative to the current directory (i.e., the directory in which a user is currently working). An absolute path (also called a full path ) is an address relative to the root directory (i.e., the directory at the very top of the filesystem and which contains all other directories and files).
    [Show full text]
  • Answers to Even- Numbered Exercises 5
    Answers to Even- Numbered Exercises 5 from page 163 1. What does the shell ordinarily do while a command is executing? What should you do if you do not want to wait for a command to finish before running another command? 2. Using sort as a filter, rewrite the following sequence of commands: $ sort list > temp $ lpr temp $ rm temp $ cat list | sort | lpr 3. What is a PID number? Why are they useful when you run processes in the background? 4. Assume that the following files are in the working directory: $ ls intro notesb ref2 section1 section3 section4b notesa ref1 ref3 section2 section4a sentrev Give commands for each of the following, using wildcards to express filenames with as few characters as possible. 1 2 Chapter 5 Answers to Exercises a. List all files that begin with section. $ ls section* b. List the section1, section2, and section3 files only. $ ls section[1-3] c. List the intro file only. $ ls i* d. List the section1, section3, ref1, and ref3 files. $ ls *[13] 5. Refer to the documentation of utilities in Part III or the man pages to determine what commands will a. Output the number of lines in the standard input that contain the word a or A. b. Output only the names of the files in the working directory that contain the pattern $(. c. List the files in the working directory in their reverse alphabetical order. d. Send a list of files in the working directory to the printer, sorted by size. 6. Give a command to a. Redirect the standard output from a sort command into a file named phone_list.
    [Show full text]
  • Your Performance Task Summary Explanation
    Lab Report: 11.2.5 Manage Files Your Performance Your Score: 0 of 3 (0%) Pass Status: Not Passed Elapsed Time: 6 seconds Required Score: 100% Task Summary Actions you were required to perform: In Compress the D:\Graphics folderHide Details Set the Compressed attribute Apply the changes to all folders and files In Hide the D:\Finances folder In Set Read-only on filesHide Details Set read-only on 2017report.xlsx Set read-only on 2018report.xlsx Do not set read-only for the 2019report.xlsx file Explanation In this lab, your task is to complete the following: Compress the D:\Graphics folder and all of its contents. Hide the D:\Finances folder. Make the following files Read-only: D:\Finances\2017report.xlsx D:\Finances\2018report.xlsx Complete this lab as follows: 1. Compress a folder as follows: a. From the taskbar, open File Explorer. b. Maximize the window for easier viewing. c. In the left pane, expand This PC. d. Select Data (D:). e. Right-click Graphics and select Properties. f. On the General tab, select Advanced. g. Select Compress contents to save disk space. h. Click OK. i. Click OK. j. Make sure Apply changes to this folder, subfolders and files is selected. k. Click OK. 2. Hide a folder as follows: a. Right-click Finances and select Properties. b. Select Hidden. c. Click OK. 3. Set files to Read-only as follows: a. Double-click Finances to view its contents. b. Right-click 2017report.xlsx and select Properties. c. Select Read-only. d. Click OK. e.
    [Show full text]
  • Powerview Command Reference
    PowerView Command Reference TRACE32 Online Help TRACE32 Directory TRACE32 Index TRACE32 Documents ...................................................................................................................... PowerView User Interface ............................................................................................................ PowerView Command Reference .............................................................................................1 History ...................................................................................................................................... 12 ABORT ...................................................................................................................................... 13 ABORT Abort driver program 13 AREA ........................................................................................................................................ 14 AREA Message windows 14 AREA.CLEAR Clear area 15 AREA.CLOSE Close output file 15 AREA.Create Create or modify message area 16 AREA.Delete Delete message area 17 AREA.List Display a detailed list off all message areas 18 AREA.OPEN Open output file 20 AREA.PIPE Redirect area to stdout 21 AREA.RESet Reset areas 21 AREA.SAVE Save AREA window contents to file 21 AREA.Select Select area 22 AREA.STDERR Redirect area to stderr 23 AREA.STDOUT Redirect area to stdout 23 AREA.view Display message area in AREA window 24 AutoSTOre ..............................................................................................................................
    [Show full text]
  • What Is UNIX? the Directory Structure Basic Commands Find
    What is UNIX? UNIX is an operating system like Windows on our computers. By operating system, we mean the suite of programs which make the computer work. It is a stable, multi-user, multi-tasking system for servers, desktops and laptops. The Directory Structure All the files are grouped together in the directory structure. The file-system is arranged in a hierarchical structure, like an inverted tree. The top of the hierarchy is traditionally called root (written as a slash / ) Basic commands When you first login, your current working directory is your home directory. In UNIX (.) means the current directory and (..) means the parent of the current directory. find command The find command is used to locate files on a Unix or Linux system. find will search any set of directories you specify for files that match the supplied search criteria. The syntax looks like this: find where-to-look criteria what-to-do All arguments to find are optional, and there are defaults for all parts. where-to-look defaults to . (that is, the current working directory), criteria defaults to none (that is, select all files), and what-to-do (known as the find action) defaults to ‑print (that is, display the names of found files to standard output). Examples: find . –name *.txt (finds all the files ending with txt in current directory and subdirectories) find . -mtime 1 (find all the files modified exact 1 day) find . -mtime -1 (find all the files modified less than 1 day) find . -mtime +1 (find all the files modified more than 1 day) find .
    [Show full text]