gethostbyaddr looping true list - python

I'm trying to get the following code working
import socket
#import dns.resolver
#my_resolver = dns.resolver.Resolver()
#my_resolver.nameservers = ['192.168.1.2']
ip_list = []
for ip in range(1, 256):
ip_list.append('192.168.1.' + str(ip))
with open(os.devnull, "wb") as limbo:
for ip in ip_list:
name = socket.gethostbyaddr(ip)
print(name)
my problem is that at the moment the ip has no registration in the DNS it gives an error
File "/data/opt/python/resolv.py", line 15, in <module>
name = socket.gethostbyaddr(ip)
socket.herror: [Errno 1] Unknown host
How can I solve this
I'm using python2 due to some limitations
Thanks in regards.

the error ecours because there is the ip address you tried does not exists.
you can try catch the with try and except, or check if they are up.
try and except:
import socket
#import dns.resolver
#my_resolver = dns.resolver.Resolver()
#my_resolver.nameservers = ['192.168.1.2']
ip_list = []
for ip in range(1, 256):
ip_list.append('192.168.1.' + str(ip))
with open(os.devnull, "wb") as limbo:
for ip in ip_list:
try:
name = socket.gethostbyaddr(ip)
print(name)
except:
continue
check if up:
import socket
#import dns.resolver
#my_resolver = dns.resolver.Resolver()
#my_resolver.nameservers = ['192.168.1.2']
ip_list = []
for ip in range(1, 256):
ip_list.append('192.168.1.' + str(ip))
HOST_UP = True if os.system("ping -c 5 " + SOMEHOST.strip(";")) is 0 else False
with open(os.devnull, "wb") as limbo:
for ip in HOST_UP:
try:
name = socket.gethostbyaddr(ip)
print(name)
except:
continue

Related

python Port scanner that reads ports from . txt

My issue is that I have a ports.txt file in it has 4 port numbers. I wish for this program to scan all port numbers specified within the txt file. currently It will only scan the first port number listed in the txt file against the 40 odd IP addresses. I hope my formatting is correct and my detail is enough. ty
import socket
import os
import sys
from datetime import datetime
import win32evtlogutil
import win32evtlog
def main():
### call step 1 function
ipList = network_addr()
# call step 2 function
portList = read_ports()
print(portList)
#call step 3 function
for ip in ipList:
for port in portList:
scan_ports(ip,port)
# call step 4 function
report_to_EventViewer(ipList[0:10], 2) # warning
#report_to_EventViewer(ipList, 1) # error
# processing inputs
# Step 1: process input 1 (subnet or network address):
def network_addr():
while True:
ip_list = []
subnet_Addr = input('Enter a Class-C Network Address or subnet with format (x.x.x): ')
subnet = subnet_Addr.split('.') # subnet is a list of 3 items (octets)
try:
if (len(subnet)==3 and 192<=int(subnet[0])<=223 and 0<=int(subnet[1])<=255 and 0<=int(subnet[2])<=255):
#return subnet_Addr
print('valid subnet: ',subnet_Addr)
for ip in range(11,40,2):
ip_temp = subnet_Addr + '.' + str(ip)
ip_list.append(ip_temp)
return ip_list
else:
value = 'wrong subnet entered'
print(value)
except ValueError:
print('wrong subnet entered, octects must be digits')
# Step 2: process input 2 (read port numbers from ports.txt):
def read_ports():
with open("ports.txt", 'r') as file_path:
port_list = []
for port in file_path:
try:
if int(port) in port_list:
print(f'port: {port} already exists')
else:
port_list.append(int(port))
except:
print(f'the port number: {port} is not a valid integer')
return port_list
else:
print('ports.txt is empty \n .... Exiting Port Scan App')
sys.exit()
# Step 3: scan ports
def scan_ports(ip,port):
# to get and format system time
dateTimeObj = datetime.now()
timeStamp = dateTimeObj.strftime("%d-%b-%Y (%H:%M:%S)")
try:
# open log file
with open("ip_port_log.txt","+r") as log:
# create client socket
socket.setdefaulttimeout(0.1)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((ip,port))
if result == 0:
data = "IP:" + ip + ":" + str(port) + " Open " + timeStamp
# write_to_console or display on screen
print(data)
# write in log file
log.write(data + "\n")
else:
data = "IP:" + ip + ":" + str(port) + " Closed/Filtered or host is offline " + timeStamp
# write_to_console or display on screen
print(data)
# write in log file
log.write(data + "\n")
# close the client socket
sock.close()
except socket.error:
print("Can't connect to IP: ", ip)
sys.exit()
except KeyboardInterrupt:
print("User pressed Ctrl+c")
sys.exit()
# Step 4: Report to Event Viewer
# output 3
def report_to_EventViewer(mylist, eventtype):
IP_EVT_APP_NAME = " CheckIPPort - IP-Port Scan Application"
IP_EVT_ID = 7040 ##According to ???
IP_EVT_CATEG = 9876 ##According to ???
IP_EVT_TYPE = win32evtlog.EVENTLOG_WARNING_TYPE # WARNING=2
IP_EVT_ERR = win32evtlog.EVENTLOG_ERROR_TYPE # ERROR=1
IP_EVT_STRS = mylist
IP_EVT_DATA = b"Scan IP Address Event Data"
win32evtlogutil.ReportEvent(IP_EVT_APP_NAME, \
IP_EVT_ID, \
eventCategory=IP_EVT_CATEG, \
eventType=eventtype, \
strings=IP_EVT_STRS, \
data=IP_EVT_DATA)
main()
you issue is in your read_ports method, you return inside the loop so it will ALWAYS only read the first one. Rewrite the method to something like:
def read_ports():
with open("ports.txt", 'r') as file_path:
port_list = []
for port in file_path:
try:
if int(port) in port_list:
print(f'port: {port} already exists')
else:
port_list.append(int(port))
except:
print(f'the port number: {port} is not a valid integer')
if not len(port_list):
print('ports.txt is empty \n .... Exiting Port Scan App')
sys.exit()
return port_list

Port scan results export to CSV

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)

How to pass inputs from file to dns.resolver.Resolver.query() from file in dns python?

I am writing a code to pass domain name and ip address from file to dns resolver query. But it does not seem to be working
import dns.resolver
import os
import sys
d = open(str(sys.argv[1]),'r') #contains the domain name list
ip = open(str(sys.argv[2]),'r') # contain the list of ip address as dns resolver
domain_list = d.readlines()
ip_list = ip.readlines()
my_resolver = dns.resolver.Resolver()
output_f = open("output.txt",'a')
for nameserv in ip_list:
my_resolver.nameservers = [nameserv]
for domain in domain_list:
try:
answer = my_resolver.query(domain)
entry = "server : " + " " + nameserv + " " + "query_result " + str(answer) + '\n'
output_f.write(entry)
except :
print domain,nameserv
print "no domain"
d.close()
ip.close()
output_f.close()
My ip address list contains 8.8.8.8 and 127.0.1.1 which are both valid dns resolvers. domain list contain www.facebook.com,www.urltrends.com etc
Still i am getting error that no domain exists.
readlines() also reads the trailing \n, which then gets passed to the resolver. Try this instead:
my_list = open(filename, 'r').read().splitlines()

Unable to ssh to remote server using paramiko module

I am trying to ssh to a remote server using python paramiko module. I need to include the key file dynamically. My code is given below.
import getpass
import paramiko
server = raw_input("What is the server name? ")
username = raw_input("Enter the username: ")
passphrase = getpass.getpass(prompt="Enter your passphrase: ")
key = '/home/%s/.ssh/id_rsa' % username
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(server, username=username, password=passphrase, key_filename=key)
stdin, stdout, stderr = ssh.exec_command('df -h')
print stdout.readlines()
ssh.close()
I am able to work with the code if I provide the key path directly instead of using the variable.
The error I am getting is:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/paramiko/client.py", line 237, in connect
for (family, socktype, proto, canonname, sockaddr) in socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known`enter code here`
seems like you have some dns error here, Pasting my script to get ssh status over here, that is dealing all the exceptions (at least I have noted so far)
#!/bin/python3
import threading, time, paramiko, socket, getpass
from queue import Queue
locke1 = threading.Lock()
q = Queue()
#Check the login
def check_hostname(host_name, pw_r):
with locke1:
print ("Checking hostname :"+str(host_name)+" with " + threading.current_thread().name)
file_output = open('output_file','a')
file_success = open('success_file','a')
file_failed = open('failed_file','a')
file_error = open('error_file','a')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(host_name, username='root', password=pw_r, timeout=5)
#print ("Success")
file_success.write(str(host_name+"\n"))
file_success.close()
file_output.write("success: "+str(host_name+"\n"))
file_output.close()
# printing output if required from remote machine
#stdin,stdout,stderr = ssh.exec_command("hostname&&uptime")
#for line in stdout.readlines():
# print (line.strip())
except paramiko.SSHException:
# print ("error")
file_failed.write(str(host_name+"\n"))
file_failed.close()
file_output.write("failed: "+str(host_name+"\n"))
file_output.close()
#quit()
except paramiko.ssh_exception.NoValidConnectionsError:
#print ("might be windows------------")
file_output.write("failed: " + str(host_name + "\n"))
file_output.close()
file_failed.write(str(host_name+"\n"))
file_failed.close()
#quit()
except socket.gaierror:
#print ("wrong hostname/dns************")
file_output.write("error: "+str(host_name+"\n"))
file_output.close()
file_error.write(str(host_name + "\n"))
file_error.close()
except socket.timeout:
#print ("No Ping %%%%%%%%%%%%")
file_output.write("error: "+str(host_name+"\n"))
file_output.close()
file_error.write(str(host_name + "\n"))
file_error.close()
ssh.close()
def performer1():
while True:
hostname_value = q.get()
check_hostname(hostname_value,pw_sent)
q.task_done()
if __name__ == '__main__':
print ("This script checks all the hostnames in the input_file with your standard password and write the outputs in below files: \n1.file_output\n2.file_success \n3.file_failed \n4.file_error \n")
f = open('output_file', 'w')
f.write("-------Output of all hosts-------\n")
f.close()
f = open('success_file', 'w')
f.write("-------Success hosts-------\n")
f.close()
f = open('failed_file', 'w')
f.write("-------Failed hosts-------\n")
f.close()
f = open('error_file', 'w')
f.write("-------Hosts with error-------\n")
f.close()
with open("input_file") as f:
hostname1 = f.read().splitlines()
#Read the standard password from the user
pw_sent=getpass.getpass("Enter the Password:")
start_time1 = time.time()
for i in hostname1:
q.put(i)
#print ("all the hostname : "+str(list(q.queue)))
for no_of_threads in range(10):
t = threading.Thread(target=performer1)
t.daemon=True
t.start()
q.join()
print ("Check output files for results")
print ("completed task in" + str(time.time()-start_time1) + "seconds")

Socket would not connect in Python

I'm having a problem with my code.
The connection should work but the server does not get anything, even though I'm sending data.
Could you check out my code and help me?
import socket
def inviare(ip,port):
file_name = raw_input("File name? ")
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect((ip,port))
file_open = open(file_name,"r")
file_content = file_open.read()
print file_content
sock.send(file_content)
file_open.close()
sock.close()
def ricevere(ip,port):
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind((ip,port))
sock.listen(5)
while 1:
(connection, adress) = sock.accept()
try:
file_data = sock.recv(6000)
filewrite = open("Down.txt","w")
print file_data.read()
filewrite.write(file_data.readlines())
filewrite.close
except:
pass
def main():
command = raw_input("Send or receive? ");
if(command == "receive"):
ip = raw_input("Ip ")
port = input("Port ")
ricevere(ip,port)
elif(command == "send"):
ip = raw_input("Ip ?")
port = input("Port?")
inviare(ip,port)
if __name__ == '__main__':
main()
I have tried to run it in several machines and changed lots of things, but nothing happened. Same problem, but it does not output any error!
Inside ricevere you are trying to read from your server socket (sock) and not from the connected client connection.
Hence it raises: [Errno 107] Transport endpoint is not connected
(Which you can see if you don't pass the except-clause, but actually print the exception.)
You script runs as expected, when you change your try-block to:
file_data = connection.recv(6000)
filewrite = open("Down.txt","w")
print file_data
filewrite.write(file_data)
filewrite.close()

Categories

Resources