Port scan results export to CSV - python

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)

Related

How to upload a file to server with Tkinter filedialog

I have a client that let user to browse a file and upload to a server. Currently I'm just using command terminal to operate the program. When user types in fup in the terminal, the program will ask for filename and the file will be uploaded to the server if the filename input by user is valid.
So, what I want now is letting user to browse any file directory from a GUI without typing the filename to upload. I've tried to implement filedialog but it seems like not working. When I browse and upload a file, the server does not receive any new file. I am stuck with issues almost a week already but still couldn't find any solution. Hope someone could help me. Thanks in advance.
Client.py
import socket, sys, os
from tkinter import filedialog
from tkinter import *
import time, shutil
root = Tk()
# socket creating
def sock():
try:
s = socket.socket()
host = input('Enter Target IP :')
port = 9999
s.connect((host, port))
return (host, s)
except:
print("Error: In binding")
sock()
host, s = sock()
# upload file to client
def fup(conn):
try:
filename = filedialog.askopenfilename(parent=root, initialdir="/", title='Please select a directory')
if os.path.isfile(filename):
conn.send(str("fup~" + filename).encode("utf-8"))
conn.send(str.encode("EXISTS " + str(os.path.getsize(filename))))
filesize = int(os.path.getsize(filename))
userResponse = conn.recv(1024).decode("utf-8")
if userResponse[:2] == 'OK':
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
conn.send(bytesToSend)
totalSend = len(bytesToSend)
while int(totalSend) < int(filesize):
bytesToSend = f.read(1024)
totalSend += len(bytesToSend)
conn.send(bytesToSend)
sys.stdout.write("\r|" + "█" * int((totalSend / float(filesize)) * 50) + "|{0:.2f}".format(
(totalSend / float(filesize)) * 100) + "% ")
sys.stdout.flush()
print("\nUpload Completed!")
else:
print("File Does Not Exist!")
except:
print("Error")
# download file from client
def fdown(conn):
try:
print(os.getcwd())
filename = input("\nMANO >>Filename? -> ")
if filename != 'q':
conn.send(("fdown~" + filename).encode("utf-8"))
data = conn.recv(1024).decode("utf-8")
if data[:6] == 'EXISTS':
filesize = data[6:]
msg = input("File exists, " + str(filesize) + "Bytes, download? (Y/N)? -> ").upper()
if msg == 'Y':
conn.send("OK".encode("utf-8"))
f = open(filename, 'wb')
data = (conn.recv(1024))
totalRecv = len(data)
f.write(data)
while int(totalRecv) < int(filesize):
data = conn.recv(1024)
totalRecv += len(data)
f.write(data)
sys.stdout.write("\r|" + "█" * int((totalRecv / float(filesize)) * 50) + "|{0:.2f}".format(
(totalRecv / float(filesize)) * 100) + "% ")
sys.stdout.flush()
time.sleep(0.01)
print("\nDownload Complete!")
f.close()
else:
print("File Does Not Exist!")
except:
print("Error")
# commands that perform on client
def mano(cip, conn):
fup(conn)
def run():
mano(host, s)
upload_button = Button(root, text="upload", command=run)
upload_button.place(x=130, y=17, width=50, height=22)
root.mainloop()
Server.py
import socket, os, subprocess, shutil, pickle, struct, threading
## gettig the hostname by socket.gethostname() method
hostname = socket.gethostname()
## getting the IP address using socket.gethostbyname() method
ip_address = socket.gethostbyname(hostname)
# Create a Socket ( connect two computers)
def create_socket():
try:
global host
global port
global s
host = ""
port = 9999
s = socket.socket()
except socket.error as msg:
create_socket()
# Binding the socket and listening for connections
def bind_socket():
try:
global host
global port
global s
s.bind((host, port))
s.listen(5)
## printing the hostname and ip_address
print(f"Hostname: {hostname}")
print(f"IP Address: {ip_address}")
print(f"Running Port: {port}")
except socket.error as msg:
bind_socket()
print(bind_socket())
# send file list
def flist(conn):
try:
arr = pickle.dumps(os.listdir())
conn.send(arr)
print(arr)
except:
conn.send(('Error').encode("utf-8"))
# accept file from server
def fdown(filename, conn):
try:
data = conn.recv(1024).decode("utf-8")
if data[:6] == 'EXISTS':
filesize = data[6:]
conn.send("OK".encode("utf-8"))
f = open(filename, 'wb')
data = (conn.recv(1024))
totalRecv = len(data)
f.write(data)
while int(totalRecv) < int(filesize):
data = conn.recv(1024)
totalRecv += len(data)
f.write(data)
f.close()
except:
conn.send(('Error').encode("utf-8"))
# send file
def fup(filename, conn):
if os.path.isfile(filename):
conn.send(str.encode("EXISTS " + str(os.path.getsize(filename))))
filesize = int(os.path.getsize(filename))
userResponse = conn.recv(1024).decode("utf-8")
if userResponse[:2] == 'OK':
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
conn.send(bytesToSend)
totalSend = len(bytesToSend)
while int(totalSend) < int(filesize):
bytesToSend = f.read(1024)
totalSend += len(bytesToSend)
conn.send(bytesToSend)
else:
conn.send("ERROR".encode("utf-8"))
# main
def main(s):
while True:
data = (s.recv(1024)).decode("utf-8").split('~')
if data[0] == 'fdown':
fup(data[1], s)
elif data[0] == 'fup':
fdown(data[1], s)
elif data[0] == 'flist':
flist(s)
else:
s.send(".".encode('utf-8'))
def socket_accept():
while True:
conn, address = s.accept()
t = threading.Thread(target=main, args=(conn,))
t.start()
create_socket()
bind_socket()
socket_accept()
**After I click on upload and it show uploaded compelte, but the server doesn't receive any new file.
Since you have used filedialog.askopenfilename() to get the filename which is a full pathname, like for example C:/Users/heng/PycharmProjects/testtest/New System/test.txt. So the server gets the same full pathname and try to create the output file. But it will fail if C:/Users/heng/PycharmProjects/testtest/New System/ does not exists in server side.
To fix the issue, either sending the filename part (without the directory information) in client side:
def fup(conn):
try:
filename = filedialog.askopenfilename(parent=root, initialdir="/", title='Please select a directory')
if os.path.isfile(filename):
_, basename = os.path.split(filename)
conn.send(str("fup~" + basename).encode("utf-8")) # use basename instead of filename
...
or remove the directory information in server side:
def fdown(fullname, conn): # renamed filename to fullname
_, filename = os.path.split(fullname) # get the filename part only
try:
...

Upload files from client to server and vice versa in python

Started to implement this project in C++, however I figured Python would be a better choice going forward for x-platform.
Goal here is to create a simple file server and then create a client. Client should be able to upload files to the server and download files from the server.
My code for the client is:
import socket
def Main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.connect((host,port))
choice = raw_input("Upload or Download? (u/d):")
if choice == 'd':
filename = raw_input("File to Download? (q to quit): ")
if filename != 'q':
s.send(filename)
data = s.recv(1024)
if data[:6] == "EXISTS":
filesize = long(data[6:])
message = raw_input("File found on the server!," +str(filesize)+"bytes, continue with download? y/n:")
if message == "y":
s.send('OK')
f = open('new_'+filename, 'wb')
data = s.recv(1024)
totalRecv = len(data)
f.write(data)
while totalRecv < filesize:
data = s.recv(1024)
totalRecv += len(data)
f.write(data)
print ("Percentage Completed: "+"{0:.2f}".format((totalRecv/float(filesize))*100))
print ("File has been Downloaded!")
else:
print ("File doesnt exist!")
else:
filename = raw_input("File to Upload? (q to quit): ")
# if filename != 'q':
print ("Upload Function Coming Soon")
s.close()
if __name__ == '__main__':
Main()
The code for the server is:
import socket
import threading
import os
def RetrFile(name, sock):
filename = sock.recv(1024)
if os.path.isfile(filename):
sock.send("EXISTS" + str(os.path.getsize(filename)))
userResponse = sock.recv(1024)
if userResponse[:2] == 'OK':
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
sock.send(bytesToSend)
while bytesToSend != "":
bytesToSend = f.read(1024)
sock.send(bytesToSend)
else:
sock.send("ERR")
sock.close()
def Main():
host = "127.0.0.1"
port = 5000
s = socket.socket()
s.bind((host,port))
s.listen(5)
print ("Server Started")
while True:
c, addr = s.accept()
print ("Client Connected:") + str(addr) + ">"
t = threading.Thread(target=RetrFile, args=("retrThread", c))
t.start()
s.close()
if __name__ == '__main__':
Main()
I have it just fine for the download of the file, and thinking about it, I should be able to just reverse process for the upload portion of the client (instead of fetch the download, I basically copy the server part to perform the upload)...however I just cant seem to wrap my head around how to do so. I'm not worried at this point over the hard coded port etc---will fix that later, however does anyone have any suggestions going forward with this?
I need to emphasize that I am using python < v3 (I know--its old) however its a program limitation that I need to adhere to (hence the raw_input() v. input())

print contents of file - python socket

I'm trying to print the contents of a file to the client using the defined command 'get'. I am not getting the contents of the file instead the contents are getting over written with Server Says... get test.txt.
Here is my client code:
import socket
import sys
import os
HOST = 'localhost'
PORT = 8082
size = 1024
def ls():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
s.send(userInput)
result = s.recv(size)
print result
s.close()
return
def put(commandName):
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(commandName)
string = commandName.split(' ', 1)
inputFile = string[1]
with open(inputFile, 'rb') as file_to_send:
for data in file_to_send:
socket1.sendall(data)
print 'PUT Successful'
socket1.close()
return
def get(commandName):
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(commandName)
string = commandName.split(' ', 1)
inputFile = string[1]
with open(inputFile, 'wb') as file_to_write:
while True:
data = socket1.recv(1024)
print data
if not data:
break
print data
file_to_write.write(data)
file_to_write.close()
print 'GET Successful'
#socket1.close()
return
done = False
while not done:
userInput = raw_input()
if "quit" == userInput:
done = True
elif "ls" == userInput:
ls()
else:
string = userInput.split(' ', 1)
if (string[0] == 'put'):
put(userInput)
elif (string[0] == 'get'):
get(userInput)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
s.send(userInput)
data = s.recv(size)
s.close()
print 'Received:', data
And server code:
import socket
import os
import sys
host = ''
port = 8082
backlog = 5
size = 1024
serverID = socket.gethostbyname(socket.gethostname())
info = 'SERVER ID: {} port: {}'.format(serverID, port)
print info
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
done = False
# Loop until client sends 'quit' to server
while not done:
client, address = s.accept()
data = client.recv(size)
print "Server received: ", data
if data:
client.send("Server Says... " + data)
if data == "quit":
done = True
elif data == "ls":
data = os.listdir("C://")
client.send(data[0])
else:
string = data.split(' ', 1)
dataFile = string[1]
if (string[0] == 'put'):
with open(dataFile, 'wb') as file_to_write:
while True:
data = client.recv(1024)
if not data:
break
file_to_write.write(data)
file_to_write.close()
break
print 'Receive Successful'
elif (string[0] == 'get'):
with open(dataFile, 'rb') as file_to_send:
for data in file_to_send:
client.send(data)
print 'Send Successful'
client.close()
s.close()
print "Server exiting."
You are getting the content of the file but it is empty... and your code works just because you probably run it in the same directory.
Your client open file to write (and then it is empty) and the server reads it (both code use the same file name). You probably wanted to read file from C:\ so you should change server code and replace line:
with open(dataFile, 'rb') as file_to_send:
with:
with open('C:\\' + dataFile, 'rb') as file_to_send:
No matter what you send to the server this condition is true so you get "server says..."
if data:
client.send("Server Says... " + data)
You have also several flaws in you client I think. Like your commands are sent 2 times: once in the client 'main' when you do:
s.send(userInput)
And once in the functions like get and ls :
socket1.send(commandName)

Python 3.4.2 - Socket module is not callable

from socket import *
import _thread
from My_TCP_callable import *
IP_list = []
port_list = []
def IP_find(IP_list):
IPtarget = input("Enter host to scan: ")
IP_list = []
print ('Starting scan on host ', IPtarget)
for ip in range(1, 256):
s = socket(AF_INET, SOCK_STREAM)
addr = IPtarget + str(ip)
result = s.connect_ex((addr, 135))
print (ip)
if(result == 0):
print ('IP %d: OPEN' % (addr,))
IP_list.append(str(addr))
s.close()
print("Open ports: %s" % (port_list))
sending_socket(port_list)
return
def port_find(port_list):
if __name__ == '__main__':
target = input('Enter host to scan: ')
possible_list = []
port_list = []
typ = int(input(" 1.Use standard ports \n 2.Set a range of points \n 3+.Set a number of specific points "))
if typ == 1:
possible_list = [20, 1025]
else:
for number in range(typ):
v = int(input("Set a port point: "))
possible_list.append(v)
if typ >= 3:
x = (possible_list)
else:
x = range(min(possible_list), max(possible_list))
targetIP = gethostbyname(target)
print ('Starting scan on host ', targetIP)
#scan reserved ports
for i in x:
s = socket(AF_INET, SOCK_STREAM)
result = s.connect_ex((targetIP, i))
if(result == 0):
print ('Port %d: OPEN' % (i,))
port_list.append(str(i))
s.close()
print("Open ports: %s" % (port_list))
return port_list
def sending_socket(port_list):
send_socket = input("Would you like to send a socket with this? ")
if send_socket == "yes":
port = int(input("Which port would you like to search? "))
message = input("What would you like to send? ")
My_TCP_callable.connect(targetIP, port, message)
elif send_socket == "automate":
message = "Alive"
for ports in port_list:
_thread.start_new_thread(connect ,(targetIP, ports, message))
return
IP_find(IP_list)
Every time I call this code an error comes up:
File "C:\Users\as009542\Desktop\python\Networking\scanner.py", line 81, in
<module>
IP_find(IP_list)
File "C:\Users\as009542\Desktop\python\Networking\scanner.py", line 15, in IP_find
s = socket(AF_INET, SOCK_STREAM)
TypeError: 'module' object is not callable
I've checked around and used this in other programs but I cant figure out why the socket can't create.
This code is not pretty or complete however I can't continue making it until I fix this problem, the last function 'sending_socket' is being called from a different file called 'My_TCP_callable' although this does not affect the problem I am having.
You are probably using import socket in your module My_TCP_callable
Because you use
from socket import *
from My_TCP_callable import *
Everything from each module is imported, and the socket names are clashing (preference is given to the one from My_TCP_callable.
I reproduced this behaviour with two files, test2.py which contained one line, import socket, and test.py which contained
from socket import *
from test2 import *
socket()
A good coding style is to use from ... import * very rarely, and only on modules specifically designed for it.

Python Socket Handling Multiple Connection

I'd like to let more than one client connect to my server, and have the server send them different items. For example send "hi" to the first client and "goodbye" to the second . Here's my code:
Server
import socket
file_num = 0
inp = raw_input("Name of the wordlist file = ")
inp2 = input("Number of lines for every wordlist = ")
with open(inp) as in_file:
for line_num, line in enumerate(in_file):
print line_num
if not line_num % inp2:
file_num += 1
with open("out{0}.txt".format(file_num), "a") as out_file:
out_file.writelines(line)
def upload(host, port):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(5)
filename = open("out1.txt", "rb")
print "Server Waiting for client on port ", port
while 1:
client_socket, address = server_socket.accept()
print "Connection from ", address
while 1:
for line in filename:
server_data = line
if server_data.lower() == 'q':
client_socket.send(server_data)
client_socket.close()
break
else:
client_socket.send(server_data)
client_data = client_socket.recv(1024)
if client_data.lower() == 'q':
print "Quit from client"
client_socket.close()
break
else:
print "<-- client: ", client_data
break
upload("localhost", 4000)
and then my client program
Client
import socket
port = 4000
host_server = "localhost"
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host_server, port))
z = 1
print "Type 'Q' or 'q' to QUIT"
f = open("pino.txt", "w")
while 1:
server_data = client_socket.recv(1024)
f.writelines(server_data)
if server_data.lower() == 'q':
print "Quit from server"
client_socket.close()
break
else:
print "<-- server: ", server_data
client_data = ("Sent "+str(z))
z = z+1
if client_data.lower() != 'q':
client_socket.send(client_data)
else:
client_socket.send(client_data)
client_socket.close()
break
f.close()
Hope you give me the solution cause this will be cool if it works, another thing I'd like for this program is if the filename under def upload would change for every client. For example the first client will get out1 and the 7th will get out7. Thanks in advance.
P.S. I'm new to python so if you could explain me what you changed it would be great, don't ask me to use Twisted cause Id like to do this with the normal python socket .
I've had this problem myself :-)
So what you're trying to do is have multiple connections, however usually socket uses the main thread, making it hard to have more than one connection.
To fix this we need to use something called Threading, it allows you to surpass operations onto other threads. So you need to create a new thread when every connection is made:
import socket
from _thread import *
file_num = 0
inp = raw_input("Name of the wordlist file = ")
inp2 = input("Number of lines for every wordlist = ")
with open(inp) as in_file:
for line_num, line in enumerate(in_file):
print line_num
if not line_num % inp2:
file_num += 1
with open("out{0}.txt".format(file_num), "a") as out_file:
out_file.writelines(line)
def upload(host, port):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(5)
filename = open("out1.txt", "rb")
print "Server Waiting for client on port ", port
while 1:
client_socket, address = server_socket.accept()
print "Connection from ", address
while 1:
for line in filename:
server_data = line
if server_data.lower() == 'q':
client_socket.send(server_data)
client_socket.close()
break
else:
client_socket.send(server_data)
client_data = client_socket.recv(1024)
if client_data.lower() == 'q':
print "Quit from client"
client_socket.close()
break
else:
print "<-- client: ", client_data
break
start_new_thread(upload, ("localhost", 4000))
#NOTICE!!! If this line doesn't work ^^^
#Then replace it with:
#thread.start_new_thread(upload, ("localhost", 4000))
Hope this helps! :-)
Please tell me if it doesn't,
for I have not tested this, I've just done it before :)
Thanks,
~Coolq

Categories

Resources