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))
'''
Related
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)
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.
I am trying to create an exemption that will handle non-existent ip addresses. When I type a random ip address, for instance 122.67.254.1, the program still proceeds to scan for ports instead of
raising an exception. I need for fake IPs like this to be exempted rather than for the port scanning to proceed on a non-existent host.
#!/usr/bin/env python
import socket
import sys
from datetime import datetime
# Clear the screen
# subprocess.call('clear', shell=True)
# Ask for input
remoteServer = input("Enter a remote host to scan: ")
remoteServerIP = socket.gethostbyname(remoteServer)
# Seek user input and validate format using try block
MinRange = int(input("Enter starting port number: "))
MaxRange = int(input("Enter ending port number: "))
CheckRange = range(MinRange, MaxRange + 1, 1)
# Create a function to use the command for a given host and port
def CheckPort(host, port):
s = socket
try:
s.connect((host, port))
except:
return False
else:
return True
# Every scan should create a new file. Check if file exists. If so, delete it
# Open file in append + read mode, create if does not exist
xfile = open("ScanResults", "w")
# Print a nice banner with information on which host we are about to scan
print("-" * 60)
print("Please wait, scanning remote host", remoteServerIP)
print("-" * 60)
# Check what time the scan started
t1 = datetime.now()
# Using the range function to specify ports (here it will scans all ports between 1 and 1024)
# We also put in some error handling for catching errors
try:
for port in range(MinRange, MaxRange):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result: int = sock.connect_ex((remoteServerIP, port))
if result == 0:
print("Port {}: Open".format(port))
xfile.write(result)
sock.close()
except KeyboardInterrupt:
print("You pressed Ctrl+C")
sys.exit()
except socket.gaierror:
print('Hostname could not be resolved. Exiting')
sys.exit()
except socket.error:
print("Couldn't connect to server")
sys.exit()
# Checking the time again
t2 = datetime.now()
# Calculates the difference of time, to see how long it took to run the script
total = t2 - t1
# Printing the information to screen
print('Scanning Completed in: ', total)
# notify user process has finished
start = t1
end = t2
print("Task completed. Port range", MinRange, " - ", MaxRange, " has been scanned. ")
elapsed = end - start
now = datetime.now()
dt_string = now.strftime("%m/%d/%Y %H:%M:%S")
print("Scan completed at: ", dt_string)
print("Total scan time: ", elapsed, "seconds.")
#FinTup = ["Port", globals(Newvar), "is open", "\n"]
#FinOut = ''.join(FinTup)
FinTup = ["Scan completed at", str(dt_string), "\n"]
FinOut = ''.join(FinTup)
xfile.write(FinOut)
FinTup = ("Total scan time:", str(elapsed), "seconds.", "\n")
FinOut = ''.join(FinTup)
xfile.write(FinOut)
xfile.close()
How do I export these Python scan results to a CSV file?
import socket
import urllib3
import webbrowser
import csv
target = input('[+] Enter Target IP --> ')
print("target = ", target)
startport = input("Enter start port -->")
print("Starting port = ", startport)
endport = input("Enter last port to scan -->")
print("Ending port = ", endport)
print("Running port scan on target: ", target)
for i in range(1, 445):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn = s.connect_ex((target, i))
if (conn == 0):
print("Port %d: Open" % (i))
s.close()
new = 2;
url = "https://www.tenable.com/blog/vulnerabilities-by-common-ports-dashboard"
for i in range(1, 445):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn = s.connect_ex((target, i))
if (conn == 0):
webbrowser.open("https://www.tenable.com/blog/vulnerabilities-by-common-ports-dashboard", new=2)
print("Opening website vulnerabilities by common ports")
s.close()
This code will help you storing all the open ports in csv file. All you need to do is add this code exactly in the "if" part of the code
fields=['i']
with open(r'name.csv', 'a') as f:
writer = csv.writer(f)
writer.writerow(fields)
I wanted to create a Python program that does several things. Ping all addresses in a predefined network, gather the DNS information, write a file with IP address, DNS name, ping fail or pass, date. Then run and email the resulting file to myself once a week, every Friday. I have created this program and will post my own answer. I am new to Python and was able to get this written with the help from other answers posted on this site. Thanks to all those who contributed answers on this site. Hope the answer I post will help someone else.
#!/usr/bin/python3.4
#Above statement makes sure you are using version 3.4
#when multiple versions are installed. has to be the 1st line.
# Import modules
import subprocess
import socket
import errno
import time
import datetime
import ipaddress
today = datetime.date.today()
# define DNS lookup and error handling
# return none,none,none needed otherwise if no DNS record
# the routine errors out and the program stops
def lookup(addr):
try:
return socket.gethostbyaddr(addr)
except socket.herror:
return None, None, None
# Prompt the user to input a network address
# commented out the prompt for input so it can run unattended
# net_addr = input("Enter a network address in CIDR
format(ex.192.168.1.0/24): ")
net_addr = ('192.168.1.0/24')
# Create the network
ip_net = ipaddress.ip_network(net_addr)
# Get all hosts on that network
all_hosts = list(ip_net.hosts())
# Configure subprocess to hide the console window
# removed code due to errors not windows linux
# setup online and offline count variables
offCnt = 0
onCnt = 0
# Open file and or create if it doesn't exist.
# file to be overwritten each time the program is run.
file = open("lab-ip.doc","w")
# For each IP address in the subnet,
# run the ping command with subprocess.popen interface
# Grab the DNS information for each IP address
# Print to console add counters and write to file.
for i in range(len(all_hosts)):
output = subprocess.Popen(['ping', '-c', '2', str(all_hosts[i])],
stdout=subprocess.PIPE).communicate()[0]
name,alias,addresslist = lookup(str(all_hosts[i]))
if "Destination Host Unreachable" in output.decode('utf-8'):
print(str(all_hosts[i]), " Ping Fail", str(name), today)
file.write(str(all_hosts[i]) + " Ping Fail - " + str(name) + " " + str(today) + "\n")
offCnt = offCnt + 1
elif "Request timed out" in output.decode('utf-8'):
print(str(all_hosts[i]), " Ping Fail", str(name), today)
file.write(str(all_hosts[i]) + " Ping Fail - " + str(name) + " " + str(today) + "\n")
offCnt = offCnt + 1
else:
print(str(all_hosts[i]), " Ping Pass", str(name), today)
file.write(str(all_hosts[i]) + " Ping Pass - " + str(name) + " " + str(today) + "\n")
onCnt = onCnt + 1
print ("Pass count = ", str(onCnt))
file.write("Pass count = " + str(onCnt))
print ("Fail count = ", str(offCnt))
file.write(" Fail count = " + str(offCnt))
file.close()
# Import yagmail for the actual sending function
import yagmail
yag = yagmail.SMTP('Gmail-id', 'gmail-pswd')
yag.send('email#email.com', subject = "Lab-ip List",contents = 'lab-ip.doc')
yag.send('email2#email2.com', subject = "Lab-ip List",contents = 'lab-ip.doc')
#end