Skip to main content

Posts

Showing posts with the label Python

Python example to use zip built-in function

Python code below use zip built-in function to display the list and display the sequence. The code below just display the list, but using subprocess or fabric module it can be expanded to connect or do remote tasks on the specified servers. Here's an example code on how to use zip built-in function. def main_func(): xservers = ["WebServer", "MailServer", "MonitoringServer", "KibanaServer", "DatabaseServer", "TestServer", "NetboxServer"] xips = ["192.168.25.1", "192.168.25.2", "192.168.25.3", "192.168.25.4", "192.168.25.5", "192.168.25.6", "192.168.25.7"] for indexx, itemx in enumerate(zip(xservers, xips), start=1): print(indexx, itemx[0], "=", itemx[1], " ==> VM with platform services") if __name__ == "__main__": main_func() itemx[0] ===> refers to xservers itemx[1...

Python example using multiprocessing module

With the era of multi-core CPU, parallel, concurrency or multiprocessing is quite possible now. Below is an example of a Python code that shows how to use multiprocessing module to run multiple commands. import multiprocessing import subprocess # Shell command/s Function def multi_run_command(command): try: result = subprocess.run(command, shell=True, capture_output=True, text=True) return f"Command: {command}\nOutput:\n{result.stdout}" except Exception as e: return f"Command: {command}\nError: {e}" if __name__ == "__main__": # List of dig commands to run / Replace the commands as desired commands = ["dig @1.1.1.1 google.com", "dig @8.8.4.4 yahoo.com", "dig @9.9.9.9 bing.com"] # Create and specify limit of pool worker processes with multiprocessing.Pool(processes=3) as pool: #limit to 3 cores or workers results = pool.map(multi_run_command, commands) #use the m...

Python Fabric module run local commands

Fabric is a Python library that simplifies the use of SSH for system administration tasks by running remote commands on remote system. It can be used as well to run local commands on the system. Example code below shows on how to use Fabric module to execute local commands. Below is an example on how to use Fabric. from fabric import Connection # Create a connection to the localhost connx = Connection('localhost') # Run local commands def run_local_commands(): print(f"Executing on {connx.host} as {connx.user}") # Command 1: Get the system name result_uname = connx.local("uname -s", hide=True) print("Output of 'uname':") print(result_uname.stdout) # Command 2: Get memory on the system result_mem = connx.local("free -h", hide=True) print("Output of 'system memory':") print(result_mem.stdout) # Command 3: Display ip route result_ipr = connx.local("ip r", ...

Python subprocess run local commands

Python subprocess module is quite helpful in running local commands. While Fabric module can also be used to run local commands, Fabric module is overkill to run local commands on the system. Fabric module is quite useful in running commands on remote system via SSH. Whereas subprocess mnodule is quite ideal to execute local commands on the VM, device or local server. Python code example below to run local commands with try exception to capture any errors. Code below will run the "xz" command to zip the file on the specified path. xz command will replace the specified file as an xz file. xz file won't create a new file. import subprocess try: # Run the xz command subprocess.run(['xz', '/tmp/app_log.log'], check=True) print("File successfully compressed.") except subprocess.CalledProcessError as e: print(f"Error: Command failed with exit status {e.returncode}") except FileNotFoundError: print("Error: xz comma...

Basic Python ask user to continue or exit

In a user interactive program there are times that a program might need to ask the user to proceed or exit to determine whether the program needs to continue or not. For this a prompt is necessary, and ask a user to decide and press some keys and depending on the user input, it will determine whether the code or program will continue running or not. Below is a simple Python code that will ask a user to press y or n. The code only shows how to detect the key that was pressed, of course the logic or the code can be inserted to other existing Python codes. Python code snippet, works in Python 3: import sys print("Make a choice press [y] to continue else [n] to exit") proceed_or_exit = input() if proceed_or_exit == 'y' or proceed_or_exit == 'Y': print("Y was pressed") #put some code here pass elif proceed_or_exit == 'n' or proceed_or_exit == 'N': print("N was pressed") #put some code here if necessary ...

Python create simple function

Basic function in Python. def multiply(x,y):   return x*y Sample data: x=2 y=5 z=multiply(x,y) print("Product is: ", z) print(x, " * " , y ," is equals to = ", z) Sample output: That's it, a simple and basic functin in Python! Keep your feet on the ground! and kneel down to pray! Prayer is the ultimate connection to the creator.

Python Basics - creating virtual environment and activating

 Creating virtual environment in Python is quite important thing to know if you are venturing to the world of Python Programming. Virtual Environment in Python may sound complicated at first if you haven't played around it. Let's delve into it. Why do we need a virtual environment? When we can just installed Python directly to the system. One good thing for creating Python virtual environment, is you can have multiple environments on Python on your system and also different versions. If 2 or 3 people are using the same server or computer, it won't be ideal that each person will use same environment and mess up the work of the other person. And also if your coding is good for a specific version of Python, the syntax may not work on new versions of Python and this is where virtual environment comes into the scenario. How do we create a virtual environment in Python? It's quite straight forward, here's the command. Of course this assumes that Python has been installed ...

How to automate Python to use Telnet to check ports

 Checking ports automatically can be stressful if there are quite a few addresses and ports to be checked. And typing manually is prone to error by mistyping the IP Address and Port. This is where automation comes into play. Prepare the IP Address and Port on  a text file, and once all is prepared. Let Python do the job or the task to Telnet and check the port whether the system can successfully connect or not. The tester just need to watch or monitor the terminal or do some other task, while waiting for the Python to do its job. Simple code below shows, how to do this task. #===================================== import sys import telnetlib def get_all_ips(filename_to_check):   with open(filename_to_check, 'r') as entries:     for ip_entries in entries:       ip_and_port=ip_entries.split(" ")                 the_ip=ip_and_port[0]       the_port_num=ip_and_port[1]       the_...

Linux SSH using Python and run remote commands

 SSH in Linux using Python and run commands on remote server A simple code snippet in Python to SSH to a remote system on a Linux Enviroment and run some commands Simple code snippet below, to get the serial number host on a remote system and save the output to the local host where the Python was executed. Python code snippet below is just a two-liner, that will SSH to a remote system and execute some commands and save the output locally. Save the output as "ssh_get_serial.py" or any filename as desired, and run as python3 ssh_get_serial.py. import subprocess  subprocess.Popen("ssh {user}@{host} {cmd}".format(user='root', host='server.web01.internal', cmd='s dmidecode -t system | egrep "Serial|Product";hostname > /tmp/server-sn-check.txt '), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() import subprocess <-- module to be imported in Python subprocess.Popen("ssh {user}@{host} {cmd}" {user} ...

Python Basics Read Text File and placed into variable

Python code below is a simple and basic code, that will open a text file in read only mode. Code below has been tested using Python3. It just demonstrates using a “print” statement to show the logic; how to open a file in read only mode and place the line that was read to a variable. The logic can be used on advance methods, such as replacing the line with IP Address and supplying a shutdown command to the IP Address. Here’s the code: #Open the file as Read Only with open('mysampledata.txt','r') as file_objHandler: #'mysampledata.txt' <--file name of the text file to be read #'r' <-- tell Python to open file as read only     #Read all lines in the file.     TxtLines = file_objHandler.readlines()     line_counter = 0   for Oneline in TxtLines:         #print(Oneline.strip())     line_counter += 1     print(line_counter, "<-- Line# / This is the data on...

Ping device using Python

Below is a simple Python code that accepts IP Address as input and check or ping the IP Address and shows an output whether its up or down. Some network disable ICMP request, so no matter how you try the system will not reply to the ping request. Code below is great when you're getting hands wet on simple Python script. Here's the code: #!/usr/bin/python3  import subprocess as subps  import sys  def ipcheck(check_ice):    status,result = subps.getstatusoutput("ping -c1 -w2 " + str(check_ice))    if status == 0:       print("Device " + str(check_ice) + " is UP!")       print(status,result)   else:       print("Device " + str(check_ice) + " is DOWN!") ipcheck(str(sys.argv[1]))  #================ Works great on Linux system. For Windows, run on WSL environment. Type: wsl to enable WSL Then change directory to: /mnt/c/Users/<username>/Documents  Or cd /mnt/c/<browse to wh...

Python basic if else and or comparison code

Comparing input or variables is a quite a common task to do when creating programs. In Python it can be done in a lot of ways, this example code below shows how it’s being done using “if else” and “or” statement. Here’s the example code below: #Get user input requires Python 3 input1 = input("1. Type something to test this out : ") input2 = input("2. Type something to test this out : ") input3 = input("3. Type something to test this out : ")   #variable initialization is important or else it will result to NameError: name 'variable_name' is not defined checkinput1 = 0 checkinput2 = 0 checkinput3 = 0 noinput = 1   #int(input1) convert the input1 string to an integer if (int(input1) > 40):   checkinput1 = "1" elif ( int(input2) > 40):   checkinput2 = "1" elif ( int(input3) > 40):   checkinput3 = "1" else:   noinput = 0   if (checkinput1 or checkinput2 or checkinput3 ==...

Python create multiple choices for if statement

How to compare multiple choices in Python if statement? In an if else statement, if case sensitivity is a concern on the response or input from the user. Then the expected response should be defined on the if statement. Of course, there’s a good workaround on this kind of scenario like converting all input to lowercase or uppercase then start comparing or matching. Basically, the code below is for illustration purposes only. Converting the input to lowercase or uppercase is a good option, if the program is expecting a string input. However, code illustrated below will not be useful if the input is a number. In which case, converting the input to lowercase or uppercase will not help. Anyway, code below uses the string T, True or true as possible input that will display this message” You must have seen the sun! Or hoping to see the sun at the end of the tunnel!” if it matches “T, True or true”. If the input is TRUE, or other letter other than the characters mentioned above it...

Python if else pass or continue after evaluating input

Beginning in Python programming? If else statement is quite a basic statement in any programming language. If else is used in evaluating conditions or basically, it will tell the program what to do next if a specified match or input is encountered. In if else statement, depends on the conditional statement that is set then the next logic will determine on what action or execution will be performed. For example, after a match pattern occurs then the next statement will execute an action but sometimes after a match occurs you don't want to do anything instead the else statement will show what action or logic to be executed. In Python "continue" statement does not mean that it will continue to execute the code after the "continue" statement, instead it will break that execution and goes to the top of the code and continue the next course of action. However, "pass" statement in Python will mean literal "pass". So, if "pass" is...

Use PowerShell in Excel VBA

VBA in Excel is very helpful since it can run things without any human intervention, or technically it can run task and automate things and just get the result. VBA coupled with PowerShell can even be more interesting. Of course, there is always some drawback or pros and cons. Bad actor can take advantage of VBA and PowerShell to run malicious software on user’s computer. For most users who are not aware or doesn’t believe that VBA and PowerShell can be used to steal data, one common reaction is; Is it possible? Or you are just trying to exaggerate and scare people? As the odds say, to see is to believe. Or to see it in action is one thing and trying to educate users is another thing. Cyber Security is a task that everyone should be a part of, a chain is useless if one its link is weak. Which is basically, true in digital world. The company may spend thousands of moneys on Firewall, Anti-Virus and other devices or software to thwart attack but just a simple click on a Phishin...