psutil.net bytes_recv start from 0 - python-3.x

I want to track the traffic from my NIC's since I started the Python script.
But psutil.net_io_counters().bytes_recv dosn't start at 0 byte to count. I only can change it to zero by restarting my NIC.
import re
from time import sleep
import psutil, sys
last_received = psutil.net_io_counters().bytes_recv
last_sent = psutil.net_io_counters().bytes_sent
last_total = last_received + last_sent
while True:
received = psutil.net_io_counters().bytes_recv
sent = psutil.net_io_counters().bytes_sent
total = received + sent
last_received = received
last_sent = sent
last_total = total
income = round((received / 1024 / 1024),2) #Traffic in MB
outcome = round((sent / 1024 / 1024),2) #Traffic out MB
totalIO = round((total / 1024 / 1024),2) #Total traffic MB
print("Received: " + str(income) + " MB")
print("Sent: " + str(outcome) + " MB")
sleep(1)

Related

How to assign n ports to a server in a multi client-server socket program?

I need to define n ports for each server so that i can know if any server is connected to more than 1 client than at which port the connection is taking place.
import queue
import socket
import random
import threading
import pandas as pd
UDP_IP = "127.0.0.1"
num_server = 3
num_client = 7
server_thread_list = []
client_thread_list = []
sid = []
sip = []
dip = []
connect = []
l_info= []
s_port = []
topology_buffer = queue.Queue()
def create_csv():
source_mac = sid
source_ip = sip
dest_mac = connect
destination_ip = dip
link_info = l_info
source_portno = s_port
df = pd.DataFrame()
df["Source_MAC"] = source_mac
df["Source_IP"] = source_ip
df["Source_Port_No"] = source_portno
df["Dest_MAC"] = dest_mac
df["Dest_IP"] = destination_ip
df["Link_Info"] = link_info
print(df)
df.to_csv("network.csv", index = False)
def server(id):
UDP_PORT = 5000 + id
soc = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
soc.bind((UDP_IP,UDP_PORT))
while True:
data, addr = soc.recvfrom(1024)
data = data.decode()
data1 = "S" + str(id)
print("Server" + str(id) + "recieved message from" + str(data))
topology_buffer.put_nowait(str(data1 + "<-->" + data))
for i in range(len(data1)-1):
sid.append(data1)
ser_ip = '192.168.1.' + str(random.randint(0, 255))
sip.append(ser_ip) # generate ip address
s_port.append(UDP_PORT)
conn = data
connect.append(conn)
dest_ip = '192.168.1.' + str(random.randint(0, 255))
dip.append(dest_ip)
def client(id):
if id<= len(server_thread_list):
UDP_Port = 5000 + id
else:
UDP_Port = 5000 + random.randint(0, len(server_thread_list))
soc = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
message = ("C" + str(id))
soc.sendto(message.encode(),(UDP_IP, UDP_Port))
soc.close()
create_csv()
def topology():
while True:
link = topology_buffer.get()
print(link)
for i in range (num_server):
t = threading.Thread(target = server, args=(i,))
server_thread_list.append(t)
t.start()
for i in range (num_client):
t = threading.Thread(target = client, args=(i,))
client_thread_list.append(t)
t.start()
topology()
I want the result as, the port number to be printed along with the connection.
eg: Server S1a received message from c1 at port number 5002.
Server S1b received message from c2 at port number 5003.
Server S2b received message from c3 at port number 5004.

How to create multiple Python scripts and run them at the same time?

I have a Python script that is used to find some stresses on a structure (a crane boom) when exposed to the wind from all directions. This means it creates 360 text files, 1 for each degree the structure is facing. Instead of doing 360 consecutive loops running on a single core, I want to break the task up into maybe 10 or 20 processes. Is there a way I could modify the following code so it created and ran multiple scripts with different degree ranges i.e. one script would do 0 to 20 degrees, the next 20 to 40 etc.?
import math
import csv
boomDirection = 0
time = 0
maxStress = 650
with open("SomeWindAndHeadingStressMatrix.csv") as f:
data = [row for row in csv.reader(f)]
while boomDirection < 361:
file = open("SomeWindSpeedSourceData.txt", 'r')
data_file = open("Bolt Stress - " + str(boomDirection) + " Degrees.csv", 'w')
line = file.readline()
while line != '':
try:
if len(line.split(','))>1:
windSpeedHigh = int(int(line.split(',')[19])*1.32)
windSpeedLow = int(int(line.split(',')[22])*1.32)
windDirection = int(line.split(',')[14]) - boomDirection
if windDirection < 0:
windDirection += 360
stressHigh = float(data[windSpeedHigh][windDirection])
stressLow = float(data[windSpeedLow][windDirection])
if time % 10080 == 0:
data_file.write(str(time) + ', ' + str(maxStress) + ('\n'))
time += 0.5
else:
data_file.write(str(time) + ', ' + str(round(stressHigh,1)) + ('\n'))
time += 0.5
data_file.write(str(time) + ', ' + str(round(stressLow,1)) + ('\n'))
time += 0.5
except ValueError:
pass
line = file.readline()
data_file.close()
time = 0
boomDirection = boomDirection + 1

Parallel threads/telnet with Python: can't use len(list) > 1000

I have a program that will receive a list holding the IP addresses of routers. For each of those, a telnet connection will be triggered over an SSH tunnel.
This is working nice. Except for the fact that if the list is bigger than 1000 addresses (i.e. 1250) only the first 1000 elements will be taken into account. The first 1000 will be ok, but the remaining 250 will not even be considered.
So, first, the pseudo-code:
open ssh connection to server and bring up ssh tunnel. return local port
open telnet connection to remote router, using local port
do something
close telnet
close ssh
The number of parallel connections is a fixed integer (10, 20, 30, etc). I've tested the code with 40 parallel connections.
This is the code itself.
import ipaddress as ip
import threading
from multiprocessing.pool import ThreadPool,Pool
import paramiko
from sshtunnel import SSHTunnelForwarder
class connTelnet(threading.Thread):
def __init__(self,thrdNum, script, loopback):
threading.Thread.__init__(self)
self.num = thrdNum
self.script = script
self.loopback = loopback
self.strConn = "Con-" + str(self.num) + "| "
def run(self):
self.s = self.sshStart(self.strConn,self.loopback)
self.sshStatus = self.s[0]
self.sshServer = self.s[1]
self.localPort = self.s[2]
if self.sshStatus == 1:
print(self.strConn + ": Quitting....")
self.sshStop(self.sshServer,self.strConn,self.num)
def sshStart(self,strConn,loopback):
try:
sshServer = SSHTunnelForwarder(
(IP, PORT),
ssh_username = USER,
ssh_password = PASSWORD,
remote_bind_address = (loopback, 23),
)
sshServer.start()
localPort = sshServer.local_bind_port
sshStatus = 1
print(strConn + "SSH Tunnel Up: " + loopback + ":" + str(localPort))
except:
print(strConn + "Error SSH Tunnel")
sshStatus = -1
sshServer = -1
localPort = -1
return(sshStatus,sshServer,localPort)
def sshStop(self,sshServer,strConn,num):
sshServer.stop()
print(strConn + "SSH" + str(num) + " stopped ...")
def run_mi_thread(i, script, loopback):
connTelnet(i, script, loopback).run()
#### Main ####
if __name__ == '__main__':
progNumThreads = 40
n = 1010
a = '99.0.0.0'
ipaddress = ip.IPv4Address(a)
routers = [(ipaddress+x).exploded for x in range(1,n)]
threads_list = Pool(progNumThreads)
for i, router in enumerate(routers):
# We generate the config file
script = "blablabla\n"
threads_list.apply_async(run_mi_thread, args=(i, script, router))
threads_list.close()
threads_list.join()
So, as said before, if len(threads_list) <= 1000, all the routers will be served. If len(threads_list) > 1000, only the first 1000 routers will be served.
More over: it's very curious that the number is 1000. And it's always the same. Does not change with several runs of the program.
Would it related some how to amount of parallel sockets? amount of SSH tunnels?
Thanks!

Python timer stops at random times

Just a warning, my code uses the pyperclip module but you don't have to pip install it because it is just for cosmetic reasons to make it a little easier. It also reads a file but the contents in the file is not important right now and can be replaced with any file with strings separated by lines.
What I want my code to do is:
WORKING 1. I want to be able to enter in a value for each line in the file, the first number representing hours and the second representing minutes.
NOT WORKING 2. I want to start a timer for for the hours and minutes for each time inputted. After I will add a sound but that is not there yet.
Problem: I input 1 minute for it to count down and it randomly stops in the middle of the count down. I don't know why because sometimes it finishes and sometimes it doesn't.
Code: https://pastebin.com/A2tTHtmK
import re
import pyperclip
from collections import OrderedDict
import time
import sys
import winsound
islandAndTimes = {}
fileObject = open("C:\\Users\\harry\\Desktop\\Skyblock Island bossmob warps.txt", "r")
message = fileObject.read()
whatToSearch = re.compile(r'\/is warp \w+')
l1 = whatToSearch.findall(message)
for eachInList in l1:
pyperclip.copy(eachInList)
typeIslandTime = input("How long until it spawns? (hours, minutes) ")
islandAndTimes[eachInList] = typeIslandTime
newIslandAndTimes = OrderedDict(sorted(islandAndTimes.items(), key=lambda t: t[1]))
if typeIslandTime == "0":
del islandAndTimes[eachInList]
print(newIslandAndTimes)
for everyIsland in newIslandAndTimes:
for firstKey, firstValue in newIslandAndTimes.items():
print("\n")
print(firstKey)
splitValues = firstValue.split()
newHours = int(splitValues[0])
newSecond = 0
newMins = int(splitValues[1])
print(newHours, newMins)
hour = time.strftime("%H")
minute = time.strftime("%M")
print("The hour is " + hour + " the minute is " + minute)
newerHours = newHours + int(hour)
newerMinute = newMins + int(minute)
print("total secodns is " + str(int((int(newHours) * 60 * 60) + int(newMins) * 60)-20))
totalSeconds = int(newHours) * 60 * 60 + int(newMins) * 60-20
while newSecond != 19:
time.sleep(1)
if int(hour) < newerHours or int(minute) < newerMinute:
#int(hour) > newerHours or int(minute) > newerMinute
minute = time.strftime("%M")
hour = time.strftime("%H")
second = time.strftime("%S")
sys.stdout.write('\r' + str("Time until ring: " + str(newHours) + " " + str(newMins) + " " + str(newSecond)))
sys.stdout.flush()
if newSecond == 0:
newSecond = 60
newMins = newMins - 1
elif newMins == 0 and newHours > 0:
newHours = newHours - 1
newSecond = newSecond - 1
print('completed')

I need to write a program which calculates the number of hours a person has used a machine but I can not go over 23:59:59

I have this code so far. I need to write a program which prints the billing information for a machine which is hired out.
hours = 23
minutes = 81
seconds = 0
seconds_in_minute = 60
seconds_in_hour = 3600
final_seconds = seconds % 60
final_seconds2 = ((2 - len(str(final_seconds))) * "0") + str(final_seconds)
extra_minutes = int(seconds / 60)
final_minutes = (minutes + extra_minutes) % 60
final_minutes2 = ((2 - len(str(final_minutes))) * "0") + str(final_minutes)
extra_hours = int(minutes / 60)
final_hours = (hours + extra_hours)
final_hours2 = ((2 - len(str(final_hours))) * "0") + str(final_hours)
cost_for_seconds = 2
cost_for_seconds_in_full_minute = 1.6
cost_for_seconds_in_full_hour = 1.2
seconds_cost = cost_for_seconds * final_seconds
minutes_cost = cost_for_seconds_in_full_minute * (final_minutes * seconds_in_minute)
hours_cost = cost_for_seconds_in_full_hour * (final_hours * seconds_in_hour)
cost_for_seconds = 2
cost_for_seconds_in_full_minute = 1.6
cost_for_seconds_in_full_hour = 1.2
seconds_cost = cost_for_seconds * final_seconds
minutes_cost = cost_for_seconds_in_full_minute * (final_minutes * seconds_in_minute)
hours_cost = cost_for_seconds_in_full_hour * (final_hours * seconds_in_hour)
print("hours =", hours)
print("minutes =", minutes)
print("seconds =", seconds)
print("=" * 35)
print(" ", " ", "Total time: ", final_hours2, ":", final_minutes2, ":", final_seconds2 , sep = "")
print(" ", " ", "Cost: ", "$", int(seconds_cost + minutes_cost + hours_cost), sep = "")
print("=" * 35)
Which produces the output of
hours = 23
minutes = 81
seconds = 0
===================================
Total time: 24:21:00
Cost: $101376
===================================
Problem is I need it to be in the format 00:21:00
I need it so that the cost is still the same, but the hours display is never 24 hours or over.
I think what you are looking for is the modulo operation.
After calculating final_hours, you need to do :
final_hours = final_hours % 24
Your final hours will always be a value beetween 0 and 23
Just add a day for every 24 hours:
Here is a code snippet that will normalize seconds, minutes, hours, days:
extra_minutes, seconds = divmod(seconds, 60)
extra_hours, minutes = divmod(minutes + extra_minutes, 60)
extra_days, hours = divmod(hours + extra_hours, 24)
days += extra_days
and here is a way to make a string with time in HH:MM:SS zero-padded format:
"{:02d}:{:02d}:{:02d}".format(hours, minutes, seconds)
Hope it helps.

Resources