Python script for detecting if servers go down - python

So here is my code:
from os import system
from datetime import datetime
import time
import os
import subprocess
import sys
def status(ip_addr):
return os.system('ping ' + ip_addr + '> nul') == 0
statut[]
print("##################################")
print("Current time: ", str(datetime.now()))
print(" ")
with open('data.txt', 'r+') as adds:
add = [addrs.strip() for addrs in adds.readlines()]
for website in add:
stat = status(website)
if stat == 1:
stats = " is up!"
statut[website] = 1
else:
stats = " is down!"
statut[website] = 0
print(website, stats)
print("##################################")
while True:
print("Current time: ", str(datetime.now()))
print(" ")
with open('data.txt', 'r+') as adds:
add = [addrs.strip() for addrs in adds.readlines()]
for website in add:
stat = status(website)
if stat != statut[website]:
stats = " is up!"
statut[website] = stat
print(website, stats)
print("##################################")
time.sleep(240)
What I want to make out of it is to firstly learn if a server is up/down and after that, check at every 240 sec if it went the other way around - I can't however use boolean array "statut" like I intended. I would really apreciate some help with how I could make it work.

If you are just looking for a state change you could do something like this:
from os import system
from datetime import datetime
import time
def server_status(ip_addr):
if system('ping ' + ip_addr + '> nul') == 0:
return 'up'
else:
return 'down'
status_history = {}
print("##################################")
print("Current time: ", str(datetime.now()))
print(" ")
with open('data.txt', 'r+') as adds:
ipaddress = [addrs.strip() for addrs in adds.readlines()]
# Set inital state
for server in ipaddress:
status_history[server] = server_status(server)
print(f"{server} is {status_history[server]}")
print("##################################")
while True:
print("Current time: ", str(datetime.now()))
print(" ")
for server in ipaddress:
if server_status(server) != status_history[server]:
status_history[server] = server_status(server)
print(f"{server} has switched state to {status_history[server]}")
else:
print(f"{server} is still {status_history[server]}")
print("##################################")
time.sleep(10)
I would put a timeout on the while loop just in case and possible make some parts more configurable, such as the sleep.

Related

multithread pinging of IP address in Python

I have a list of IP addresses like 1000 no's. I am reading the ip_file.txt and storing the result file as result_date.txt. Below is the code that I achieved the result. But my issue is it's taking too long to execute the entire files. Can anyone suggest multithreading, please so that the desired result can be achieved quickly? Thanks in advance.
#!/usr/bin/env python
import os
import csv
import paramiko
from datetime import datetime
import time
import sys
import re
from collections import defaultdict
# Verifies your os type
from paramiko import file
OS_TYPE = os.name
# Sets the count modifier to the os type
count = '-n' if OS_TYPE == 'nt' else '-c'
def create_ip_list():
ip_list = []
with open("ip_file.txt", "r") as file:
for line in file:
ip_list.append(line.strip())
return ip_list
# fetching data
now = datetime.now()
dat = now.strftime("%d/%m/%Y")
# time = now.strftime("%H:%M:%S")
date_string = dat.replace('/', '-')
timestr = time.strftime("%d%m%Y-%H%M%S")
def ping_device(ip_list):
"""Ping ip_list and return results
return: None
rtype: None
"""
results_file = open("results_" + str(timestr) + ".txt", "w")
for ip in ip_list:
response = os.popen(f"ping {ip} {count} 1").read()
time.sleep(1.5)
#fetch Average time
print(response)
for i in response.split("\n"):
para = i.split("=")
try:
if para[0].strip() == "Minimum":
latency = para[3].strip()
print(latency)
# output1=latency[0:8].split(" ")
# test=output1[0]
# print(test)
except:
print("time run")
if "Received = 1" and "Approximate" in response:
#print(f"UP {ip} Ping Successful")
results_file.write(f"{ip},UP,{latency}" + "\n")
else:
print(f"Down {ip} Ping Unsuccessful")
results_file.write(f"{ip} Down" + "\n")
results_file.close()
if __name__ == "__main__":
ping_device(create_ip_list())
Write a function ping_one_device that takes a single ip and returns a single string giving the status. It should be easy to pull this out of ping_device.
Then
with open(results_file, "w") as results_file:
with ThreadPoolExecutor() as executor:
for result in map(ping_one_device, ip_list):
results_file.write(result)

Multithreading - writing to a file for each thread Python3

I have a Python 3 script which has the following code:
from subprocess import check_output, Popen, CalledProcessError
from os import getenv, mkdir, path
from time import sleep, time
from threading import Thread
def pgrep(proc_name):
try:
check_output(["pgrep", proc_name])
return True
except CalledProcessError:
return False
def watch_dog(proc_name, polling_rate, CONFIG_DIR):
print("Thread " + proc_name + " Started")
start_time = 0
end_time = 0
total_time = 0
while True:
if (pgrep(proc_name) and (start_time == 0)):
start_time = time()
print("TIMING " + proc_name)
elif ((not pgrep(proc_name)) and (start_time != 0)):
end_time = time()
total_time = str(end_time - start_time)
print("Done timing " + proc_name)
print("TIME: " + total_time)
try:
with open(CONFIG_DIR + proc_name + "-time.log", "w+") as log_file:
log_file.write(total_time)
log_file.write("\n")
log_file.flush()
except:
print("CANNOT WRITE TO FILE")
start_time = 0
end_time = 0
total_time = 0
sleep(polling_rate)
for each in processes:
globals()[each] = Thread(target=watch_dog, args=(each, polling_rate, CONFIG_DIR,))
globals()[each].start()
Everything works perfectly, except that I cannot write to any files from the watch_dog function. I have done some research, and most things are pointing towards needing a separate thread to write to the file others are wanting to write to. However, all these examples I find are for specifically multiple threads writing to one file. I, however, want one file per thread.
Is there some way to circumvent this issue or do I have to have a thread for writing to each separate file?
Discovered what my problem was. On this line:
with open(CONFIG_DIR + proc_name + "-time.log", "w+") as log_file:
CONFIG_DIR does not end with a forward slash ("/") and so the files WERE being created, just in the parent directory and with a name I did not expect. it was a simple fix:
with open(CONFIG_DIR + "/" + proc_name + "-time.log", "w+") as log_file:
Moral of the story: check your file paths.

CSV output to multiple columns instead of 1 column

So I found nmap and print(nm.csv()) help needed to print out to csv.file that gave me the code I am working with now. The last few lines of code where the def is.
But the csv file that is generated has all the data in one column. Is there a way to force it to put each data set in its own column? Or should I stick with using Excel to separate after the fact?
The data I am "printing" is formatted like this; and I believe is a key pair.
'host;hostname;hostname_type;protocol;port;name;state;product;extrainfo;reason;version;conf;cpe'
...
import sys
import os
import nmap
from datetime import datetime
import time
import csv
#Ask for user input and assign IP\subnet and port range.
print("_" * 40) #style options
ip_range = '192.168.3.132' #str(input('\nEnter an IP or subnet: '))
user_ports = '100-200' #str(input('\nEnter Ports to scan: '))
print("\nScanning IP " + ip_range + ". For ports " + user_ports + ".")
#add banner containing time stamps.
before = datetime.now()
print("_" * 40) #style options
print("\nScanning Target "+ip_range)
print('\n') #style options
print("Time Started: "+ str(datetime.now().strftime('%m-%d-%Y %H:%M:%S'))+'\n')
print("~" * 40)#style options
print('\n')#style options
#name scan configuration
nmap_scan = nmap.PortScanner()
nmap_scan.scan(str(ip_range), str(user_ports))
#printing out ports that are up
for host in nmap_scan.all_hosts():
print("Host: %s (%s)" % (host, nmap_scan[host].hostname()))
print("state: %s" % nmap_scan[host].state())
for proto in nmap_scan[host].all_protocols():
print("\n")
print("Protocol used: %s" % proto)
lport = sorted(nmap_scan[host][proto].keys())
for port in lport:
print("Port: %s\tState: %s" % (port, nmap_scan[host][proto][port]['state']))
print('\n')#style options
#export nmap scan to csv file
#export nmap scan to csv file
def save_csv_data(nmap_scan_csv, path='.'):
with open(path + '/output.csv', 'w') as output:
output.write(nmap_scan_csv)
if (len(sys.argv) > 1 and sys.argv[1]):
save_csv_data(nmap_scan.csv(), path=sys.argv[1])
else:
save_csv_data(nmap_scan.csv())
print("_" * 50)#style options
print('\n\n')#style options
#Finished time
after = datetime.now()
print("Time finished: "+ str(datetime.now().strftime('%m-%d-%Y %H:%M:%S')))
#time elapsed during scan
print('\n')#style options
delta = after-before
print("Time elapsed: " + str(delta))
'''

Python Keylogger - Not keeping Keyboard Listener open upon execution from CMD

BEFORE WE START...
I am fairly new to Python and any assistance or insight would be absolutely great.
This is NOT malicious keylogger, nor a virus, and is going to be used by my company to monitor network PCs for security purposes ONLY. It does not send logs and stores the files locally. It will not attempt to remain hidden. I am an enterprise programmer with no malicious intent. Users will be made aware that keystrokes are being monitored, and logs are stored in the user's home directory.
My Python works perfectly fine and as expected in the IDLE editor. However upon running the code from the command line, it does not continue to execute and the script exits.
I have attempted to port my code line by line to a different working version, removing any extra content. Adding a single line break or import appears to completely break the script.
The following code works and does not exit upon execution. It continues to log and works as expected. When ran from CMD, the process remains open:
from os.path import expanduser
home = expanduser("~")
from pynput.keyboard import Key, Listener
import logging
log_dir = r"{}/".format(home)
logging.basicConfig(filename = (log_dir + "log.txt"), level=logging.DEBUG, format='%(asctime)s: %(message)s')
def on_press(key):
logging.info(str(key))
with Listener(on_press=on_press) as listener:
listener.join()
However the following code does not continue to log after execution and the program exits:
from pynput.keyboard import Key, Listener
import time
import os
import random
import requests
import socket
import platform
import win32api
import wmi
import urllib.request
import logging
from os.path import expanduser
homeDir = expanduser("~")
SystemType = platform.system()
SystemArchitecture = platform.machine()
SystemPlatform = platform.platform()
SystemProcessor = platform.processor()
VolumeInformation = win32api.GetVolumeInformation("C:\\")
HostName = socket.gethostname()
SystemWMI = wmi.WMI()
publicIP = requests.get('https://api.ipify.org').text
privateIP = socket.gethostbyname(socket.gethostname())
user = os.path.expanduser('~').split('\\')[2]
datetime = time.ctime(time.time())
file = open(homeDir + "\logger.txt", "w+")
file.write("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n")
print("Hostname: " + HostName)
file.write("Hostname: " + HostName + "\n")
print("User: " + user)
file.write("User: " + user + "\n")
print("Public IP: " + publicIP)
file.write("Public IP: " + publicIP + "\n")
print("Private IP: " + privateIP)
file.write("Private IP: " + privateIP + "\n")
for interface in SystemWMI.Win32_NetworkAdapterConfiguration (IPEnabled=1):
print("MAC Address: " + interface.MACAddress)
file.write("MAC Address: " + interface.MACAddress + "\n")
print("Interface Description: " + interface.Description)
file.write("Interface Description: " + interface.Description + "\n\n")
print()
file.write("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n")
if(SystemType == "Windows"):
print("System Type: " + SystemType)
file.write("System Type: " + SystemType + "\n")
print("System Architecture: " + SystemArchitecture)
file.write("System Architecture: " + SystemArchitecture + "\n")
print("System Platform: " + SystemPlatform)
file.write("System Platform: " + SystemPlatform + "\n")
print("System Processor: " + SystemProcessor)
file.write("System Processor: " + SystemProcessor + "\n\n")
DriveList = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ActiveDrives = ['%s:' % d for d in DriveList if os.path.exists('%s:' % d)]
DRIVE_TYPES = {
0 : "Unknown",
1 : "No Root Directory",
2 : "Removable Disk",
3 : "Local Disk",
4 : "Network Drive",
5 : "Compact Disc",
6 : "RAM Disk"
}
print()
file.write("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n")
print("Drives In Use: ")
file.write("Drives In Use: \n")
print(ActiveDrives)
file.write(str(ActiveDrives) + "\n\n")
print()
file.write("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n")
print("Drive Types: ")
file.write("Drive Types: \n\n")
for drive in SystemWMI.Win32_LogicalDisk ():
print(drive.Caption, DRIVE_TYPES[drive.DriveType])
file.write(drive.Caption)
file.write(DRIVE_TYPES[drive.DriveType] + "\n")
print()
file.write("\n=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n")
print("C:\\ Volume Information")
file.write("C:\\ Volume Information: \n")
print(VolumeInformation)
file.write(str(VolumeInformation) + "\n\n")
print()
file.write("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n")
print("OS Instance Information: ")
file.write("OS Instance Information: \n")
for os in SystemWMI.Win32_OperatingSystem():
print(os)
file.write(str(os) + "\n")
print()
file.write("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n")
print("Logging keystrokes...")
file.write("Logging keystrokes...\n\n")
file.close()
log_dir = r"{}/".format(homeDir)
logging.basicConfig(filename = (log_dir + "logger.txt"), level=logging.DEBUG, format='%(asctime)s: %(message)s')
def on_press(key):
print(key)
logging.info(str(key))
with Listener(on_press=on_press) as listener:
listener.join()
Even adding a single import to the working version breaks it. There are no exceptions thrown.
The code is expected to continue to log keystrokes after execution, however is exiting without any error codes. It works as expected in IDLE and continues to log until IDLE is closed. However when ran from CMD it closes right after it outputs "Logging Keystrokes...".
Help?
Come to find out, it was the antivirus on the PC that was causing the program to crash. This works normally and as expected from the getgo.

Python just let main thread sleep

I use time.sleep() in my main thread and want just this thread to sleep. The problem is, that all the other threads I created in the main are sleeping too. One problem might be that they have to access a global variable.
The aim is just to not create too many threads at one time - so I count the running threads and if they are > 200 I want to let the main thread sleep to give the other threads more time.
import requests
import ipaddress
import sys
import threading
import time
loginIndicators = ["username", "user name", "password", "passwort", "log in", "sign in", "anmelden", "signin", "login", "submit", "account", "user", "pass", "id", "authentification", "authentication", "auth", "authorization", "access", "passphrase", "key"]
scancounter = 0
def scan(ip, port, protocol):
global scancounter
global file
try:
res = requests.get(protocol + "://" + ip.exploded + ":" + port + "/", timeout=1)
except:
return
finally:
scancounter += 1
if res.status_code == 401 or any(indicator in res.text.lower() for indicator in loginIndicators):
print("Found: " + ip.exploded + ":" + port + " --> " + protocol)
file.write(protocol + "://" + ip.exploded + ":" + port + "\n")
def output_status(end):
global scancounter
if(end):
time.sleep(3)
print("Scanned: " + str(int(scancounter / len(ports) / 2)))
try:
if __name__ == "__main__":
try:
nw = ipaddress.ip_network(input("Enter the starting IP address: "))
except:
print("Invalid format - expected: IP/prefix")
sys.exit()
ports = input("Enter the ports that should be tested: ")
if ports == "":
ports = ["80","8080","443"]
else:
ports = ports.replace(" ", "")
ports = ports.split(",")
file = input("Output file path: ")
if file != "":
file = open(file, "a")
iprange = nw.hosts()
try:
skip = input("How many addresses do you want to skip: ")
if skip == "":
skip = 0
for i in range(0, int(skip)):
next(iprange)
except:
print("You can't skip more addresses than the IP range contains!")
for ip in iprange:
for port in ports:
threading.Thread(target=scan, args=(ip, port, "http",)).start()
threading.Thread(target=scan, args=(ip, port, "https",)).start()
threading.Thread(target=output_status, args=(True,)).start()
except KeyboardInterrupt:
threading.Thread(target=output_status, args=(True,)).start()
Why aren't you calling output_status in the main thread rather than starting a thread for it?
threading.Thread(target=output_status, args=(True,)).start()
If you did that the sleep would occur on the main thread.
output_status(True)

Categories

Resources