script examples:

 computermonitor

#source

#https://medium.com/the-andela-way/machine-monitoring-tool-using-python-from-scratch-8d10411782fd
#!/usr/bin/env python

import os
import subprocess
import re
import shutil
def get_statistics():
statistics = {}
matcher = re.compile(‘\d+’)
# Top command on mac displays and updates sorted information about processes.

top_command = subprocess.run([‘top’, ‘-l 1’, ‘-n 0’], stdout=subprocess.PIPE).stdout.decode(‘utf-8’).split(‘\n’)

# Get Physical and Logical CPU Count
physical_and_logical_cpu_count = os.cpu_count()
statistics[‘physical_and_logical_cpu_count’] = physical_and_logical_cpu_count
“””
# Load average
# This is the average system load calculated over a given period of time of 1, 5 and 15 minutes.
# In our case, we will show the load average over a period of 15 minutes.
 
# The numbers returned by os.getloadavg() only make sense if
# related to the number of CPU cores installed on the system.
 
# Here we are converting the load average into percentage. The higher the percentage the higher the load
“””

cpu_load = [x / os.cpu_count() * 100 for x in os.getloadavg()][-1]
statistics[‘cpu_load’] = round(cpu_load)

# Memory usage
total_ram = subprocess.run([‘sysctl’, ‘hw.memsize’], stdout=subprocess.PIPE).stdout.decode(‘utf-8’)
vm = subprocess.Popen([‘vm_stat’], stdout=subprocess.PIPE).communicate()[0].decode(‘utf-8’)
vmLines = vm.split(‘\n’)

wired_memory = (int(matcher.search(vmLines[6]).group()) * 4096) / 1024 ** 3
free_memory = (int(matcher.search(vmLines[1]).group()) * 4096) / 1024 ** 3
active_memory = (int(matcher.search(vmLines[2]).group()) * 4096) / 1024 ** 3
inactive_memory = (int(matcher.search(vmLines[3]).group()) * 4096) / 1024 ** 3

# Used memory = wired_memory + inactive + active

statistics[‘ram’] = dict({
‘total_ram’: int(matcher.search(total_ram).group()) /1024**3,
‘used_ram’: round(wired_memory + active_memory + inactive_memory, 2),
})

# Disk usage
# Get total disk size, used disk space, and free disk

total, used, free = shutil.disk_usage(“/”)

# Number of Read and write operations
# from the top command, the read written result will be as follows
# ‘Disks: XXXXXX/xxG read, XXXX/xxG written.’
# we thus need to extract the read and written from this.
read_written = top_command[9].split(‘:’)[1].split(‘,’)
read = read_written[0].split(‘ ‘)[1]
written = read_written[1].split(‘ ‘)[1]

statistics[‘disk’] = dict(
{
‘total_disk_space’: round(total /1024**3, 1),
‘used_disk_space’: round(used /1024**3, 1),
‘free_disk_space’: round(free /1024**3, 1),
‘read_write’: {
‘read’: read,
‘written’: written
}
}
)

# Network latency
“””
Here we will ping google at an interval of five seconds for five times and record the
min response time, average response time, and the max response time.
“””
ping_result = subprocess.run([‘ping’, ‘-i 5’, ‘-c 5’, ‘google.com’], stdout=subprocess.PIPE).stdout.decode(
‘utf-8’).split(‘\n’)

min, avg, max= ping_result[-2].split(‘=’)[-1].split(‘/’)[:3]
statistics[‘network_latency’] = dict(
{
‘min’: min.strip(),
‘avg’: avg.strip(),
‘max’: max.strip(),
}
)
return statistics
statistics = get_statistics()
print (statistics)

Output in terminal:

berndgerstner@Bernds-MacBook-Pro python % /Library/Frameworks/Python.framework/Versions/3.9/bin/python3 /Users/berndgerstner/Desktop/python/monitor.py
{‘physical_and_logical_cpu_count’: 16, ‘cpu_load’: 9, ‘ram’: {‘total_ram’: 32.0, ‘used_ram’: 22.76}, ‘disk’: {‘total_disk_space’: 931.5, ‘used_disk_space’: 14.0, ‘free_disk_space’: 609.0, ‘read_write’: {‘read’: ‘272339/3811M’, ‘written’: ‘173045/2079M’}}, ‘network_latency’: {‘min’: ‘29.455’, ‘avg’: ‘38.259’, ‘max’: ‘51.020’}}

 digitalclock

#source

#source: https://github.com/geekcomputers/Python/blob/master/digital_clock.py
# master
# importing whole module
# use Tkinter to show a digital clock
# using python code base

import time
#because we need digital clock , so we are importing the time library.
# master
from tkinter import *
from tkinter.ttk import *

# importing strftime function to
# retrieve system’s time
from time import strftime

# creating tkinter window
root = Tk()
root.title(‘Clock’)

# master

# This function is used to
# display time on the label
def def_time():
string = strftime(‘%H:%M:%S %p’)
lbl.config(text = string)
lbl.after(1000, time)

# Styling the label widget so that clock
# will look more attractive
lbl = Label(root, font = (‘calibri’, 40, ‘bold’, ‘italic’),
background=’Black’,
foreground=’Green’)

# Placing clock at the centre
# of the tkinter window
lbl.pack(anchor = ‘center’)
def_time()

mainloop()
# =======
label = Label(root, font=(“Arial”, 30, ‘bold’), bg=”black”, fg=”white”, bd =30)
label.grid(row =0, column=1)

#function to declare the tkniter clock
def dig_clock():
 
text_input = time.strftime(“%H : %M : %S”) # get the current local time from the PC
 
label.config(text=text_input)
 
# calls itself every 200 milliseconds
# to update the time display as needed
# could use >200 ms, but display gets jerky
 
label.after(200, dig_clock)
 
# calling the function
dig_clock()

root.mainloop()
# master

 email

#source

#!/usr/bin/python -tt
#source: https://stackoverrun.com/de/q/2151234
from email.mime.text import MIMEText
from datetime import date
import smtplib
SMTP_SERVER = “smtp.web.de”
SMTP_PORT = 587
SMTP_USERNAME = “me”
SMTP_PASSWORD = “mypassword”
EMAIL_TO = [“receiver01@web.de”, “receiver02@web.de”]
EMAIL_FROM = “sender@web.de”
EMAIL_SUBJECT = “Demo Email Titel”
DATE_FORMAT = “%d/%m/%Y”
EMAIL_SPACE = “, “
DATA=’This is the content of the email.’
def email():
msg = MIMEText(DATA)
msg[‘Subject’] = EMAIL_SUBJECT + ” %s” % (date.today().strftime(DATE_FORMAT))
msg[‘To’] = EMAIL_SPACE.join(EMAIL_TO)
msg[‘From’] = EMAIL_FROM
mail = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
mail.starttls()
mail.login(SMTP_USERNAME, SMTP_PASSWORD)
mail.email(EMAIL_FROM, EMAIL_TO, msg.as_string())
mail.quit()
if __name__==’__main__’:
email()

 helloworld

print (‘Hello’,’World’)

 instagram

#source

#source: https://okhlopkov.medium.com/how-to-watch-million-instagram-stories-with-python-e71f5f077944
“””
Watch user likers stories!
This script could be very useful to attract someone’s
audience to your account.

 

If you will not specify the user_id, the script will use
your likers as targets.

 

Dependencies:
pip install -U instabot

 

Notes:
You can change file and add there your comments.
“””

 

import os
import random
import sys
import time

 

# in case if you just downloaded zip with sources
sys.path.append(os.path.join(sys.path[0], “../../”))
from instabot import Bot # noqa: E402

 

bot = Bot()
bot.login()

 

if len(sys.argv) >= 2:
bot.logger.info(
“””
Going to get ‘%s’ likers and watch their stories
(and stories of their likers too).
“””
% (sys.argv[1])
)
user_to_get_likers_of = bot.convert_to_user_id(sys.argv[1])
else:
bot.logger.info(
“””
Going to get your likers and watch their stories (and stories
of their likers too). You can specify username of another user
to start (by default we use you as a starting point).
“””
)
user_to_get_likers_of = bot.user_id

 

current_user_id = user_to_get_likers_of
while True:
try:
# GET USER FEED
ifnot bot.api.get_user_feed(current_user_id):
print(“Can’t get feed of user_id=%s”% current_user_id)

 

# GET MEDIA LIKERS
user_media = random.choice(bot.api.last_json[“items”])
ifnot bot.api.get_media_likers(media_id=user_media[“pk”]):
bot.logger.info(
“Can’t get media likers of media_id=’%s’ by user_id=’%s'”
% (user_media[“id”], current_user_id)
)

 

likers = bot.api.last_json[“users”]
liker_ids = [
str(u[“pk”])
for u in likers
ifnot u[“is_private”] and”latest_reel_media”in u
][:20]

 

# WATCH USERS STORIES
if bot.watch_users_reels(liker_ids):
bot.logger.info(“Total stories viewed: %d” % bot.total[“stories_viewed”])

 

# CHOOSE RANDOM LIKER TO GRAB HIS LIKERS AND REPEAT
current_user_id = random.choice(liker_ids)

 

if random.random() <0.05:
current_user_id = user_to_get_likers_of
bot.logger.info(
“Sleeping and returning back to original user_id=%s”% current_user_id
)
time.sleep(90 * random.random() + 60)

 

exceptExceptionas e:
# If something went wrong – sleep long and start again
bot.logger.info(e)
current_user_id = user_to_get_likers_of
time.sleep(240 * random.random() + 60)

 networkinfo

#source

Attention: switch off VPN

import os
import socket
import multiprocessing
import subprocess
import os
def pinger(job_q, results_q):
“””
Do Ping
:param job_q:
:param results_q:
:return:
“””
DEVNULL = open(os.devnull, ‘w’)
whileTrue:

ip = job_q.get()

if ip isNone:
break

try:
subprocess.check_call([‘ping’, ‘-c1’, ip],
stdout=DEVNULL)
results_q.put(ip)
except:
pass
def get_my_ip():
“””
Find my IP address
:return:
“””
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((“8.8.8.8”, 80))
ip = s.getsockname()[0]
s.close()
return ip
def map_network(pool_size=255):
“””
Maps the network
:param pool_size: amount of parallel ping processes
:return: list of valid ip addresses
“””

ip_list = list()

# get my IP and compose a base like 192.168.1.xxx
ip_parts = get_my_ip().split(‘.’)
base_ip = ip_parts[0] + ‘.’ + ip_parts[1] + ‘.’ + ip_parts[2] + ‘.’

# prepare the jobs queue
jobs = multiprocessing.Queue()
results = multiprocessing.Queue()

pool = [multiprocessing.Process(target=pinger, args=(jobs, results)) for i in range(pool_size)]

for p in pool:
p.start()

# cue hte ping processes
for i inrange(1, 255):
jobs.put(base_ip + ‘{0}’.format(i))

for p in pool:
jobs.put(None)

for p in pool:
p.join()

# collect he results
whilenot results.empty():
ip = results.get()
ip_list.append(ip)

return ip_list
if __name__ == ‘__main__’:

print(‘Mapping…’)
lst = map_network()
print(lst)

Output in terminal

berndgerstner@Bernds-MacBook-Pro python % /Library/Frameworks/Python.framework/Versions/3.9/bin/python3 /Users/berndgerstner/Desktop/python/network.py
Mapping…
[‘192.168.189.1’, ‘192.168.189.46’, ‘192.168.189.155’, ‘192.168.189.174’]
berndgerstner@Bernds-MacBook-Pro python %