Bootstrap FreeKB Articles

Python (Scripting) articles


base64 Base64 encoding and decoding Booleans Getting Started with Booleans Bytes Convert byte to string Caller Script Caller script Classes Calling classes from another Python script Getting Starting with Classes Command line options Command line options flags arguments using argparse Command line options flags arguments using sys.argv Commands Install module using setup.py Temporarily configure the "python" command to invoke the "python3" command for a specific user Date and Time Date and Time Determine Time Difference epoch date and time def (function) Calling functions from another Python script Getting Started with functions Pass values into a function Return function name Return value in a function Dictionary Append to a dictionary Convert a string to a dictionary using ast Getting Started with Dictionaries Remove keys from a dictionary using del Remove keys from a dictionary using pop Rename a key in a dictionary Replace values in a dictionary Sort a Dictionary Docker Getting Started with DockerClient List Docker Containers using Python DockerClient Restart Docker Container using Python DockerClient Email Send an email exit Stop Halt or Exit Files and Directories Change file or directory owner using os.chown Change file or directory permissions using os.chmod Copy file using shutil Create a symbolic link using os.symlink Create directory using os.makedirs Create directory using os.mkdir Create Write or Append to a file (open) Determine file encoding (ascii utf) Determine file MIME type Determine file or directory owner Determine if a file or directory exists Determine if an file or directory is readable writable (os.access) Determine if an object is a file or directory (os.path.isfile isdir) dirname basename and present working directory (pwd) Download File using requests Download File using urllib File Statistics Find files using os.walk List differences between files using filecmp List files and directories Read a file (open) Read and Write to the same file Remove directory using os.removedirs Remove directory using os.rmdir Remove directory using shutil.rmtree Remove or Delete file or directory FTP Connect to an FTP Server Hashes Getting Started with Hashes hash has_key hostname hostname (socket) if elif else statement Determine if list contains if elif else statements Index Index numbers using enumerate Input Prompt Prompt a user for input (stdin) Install Install pycharm on Linux Install Python in a virtual environment on Linux Install Python on Linux IP Address Subnet Mask Default Gateway Getting Started with ipaddress JSON Determine if JSON key contains a value Determine if JSON key contains an empty list Determine if JSON key exists Getting Started with JSON Loop through JSON list Parse dictionary using json.dumps Parse dictionary using json.dumps and json.loads Parse JSON file using json.load Parse JSON using json.loads Parse JSON using json.tool Parse JSON using the json filter Pass argparse into JSON Update a JSON file Write a dictionary to a JSON file Lists Append values to the end of a list Blank out a list Combine or merge lists Convert list to string Convert string to list using split Count the elements in a list Getting Started with Lists Remove duplicate values from a list Remove elements from a list Return the last item in a list Log Logging to a log file Rotating Log Files using RotatingFileHandler Loops Break out of a loop Loop over a dictionary Looping over a list Looping over a sequence of integers using range Looping over a string using split or splitlines Move onto the next item in a loop using continue while loop match Find matching expression using find Find matching expression using re.match Math Addition and Increment (+) Division (/) Subtraction and Decrement Microsoft Credentials Obtain credentials from login.microsoftonline.com using msal PublicClientApplication Modules Creating your own modules import module List Python system paths using sys.path Native operating system commands Native operating system commands new lines Remove new lines using strip, lstrip and rstrip nslookup nslookup os.path Return and print script name Printing output Printing stdout to the console Python Interpreter Return full path to the Python interpreter using sys.executable pyvault Password Vault Random Generate random numbers and strings Replace Escape backslash Replace pattern using re.sub Replace pattern using replace REST API DELETE request GET request Location Redirects PATCH request POST request PUT Request SCP SCP using paramiko Sleep Pause using Sleep Sort Sort a List SSH SSH using paramiko strip Remove whitespace using strip, lstrip and rstrip Tokens Generate random secret tokens Troubleshooting Resolve "AttributeError: 'dict' object has no attribute 'loads'" Resolve "Could not import runpy module" Resolve "dictionary update sequence element" Resolve "Host key for server does not match" Resolve "ImportError: No module named" Resolve "IndexError: list index out of range" Resolve "No module named '_ctypes'" Resolve "partially initialized module has no attribute (most likely due to a circular import)" Resolve "Permission Denied" with Python DockerClient Resolve "pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available" Resolve "Python.h: No such file or directory" Resolve "TypeError: cannot concatenate 'str' and 'bool' objects" Resolve "TypeError: cannot concatenate 'str' and 'list' objects" Resolve "TypeError: string indices must be integers" Resolve AttributeError: 'dict' object has no attribute 'json' Resolve DeprecationWarning Resolve InsecureRequestWarning Resolve KeyError Resolve ModuleNotFoundError Resolve SSLError CERTIFICATE_VERIFY_FAILED Resolve UnicodeDecodeError try except else error handling with try except else finally Upper Lower Case Upper Lower Case using upper lower Users and Groups Return username using getpass getuser (whoami) Return users group using os.getgroups Users Home Directory Variables __name__ variable Append to a variable Defining variables undefining variables using None and del Version python --version command Virtual Environment Activate a virtual environment Create a virtual environment (venv virtualenv) Installing packages in a virtual environment Setting environment variables in a virtual environment (venv virtualenv) which Locate CLIs using shutil.which winrm Connect to Windows Host YAML Append to a YAML file using ruamel.yaml Modify YAML file ruamel.yaml Read YAML file using ruamel.yaml Remove keys from a YAML file using ruamel.yaml Write dictionary to YAML file