find IP address and port in a text file using python - python

I have a text file which have text similar to mentioned below
harry's source ip and port combination is 192.168.4.1/5897 and he is
trying to access destination 202.158.14.1/7852
The text may vary. My task is to find the first pair of IP and port.
However my code is not working
import re
with open('traffic.txt', 'r') as file:
fi = file.readlines()
re_ip = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
re_port = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$\/(\d+)")
for line in fi:
ip = re.findall(re_ip,line)
port = re.findall(re_port,line)
print port , ip

Correct code
import re
with open('traffic.txt', 'r') as file:
fi = file.readlines()
re_ip = re.compile("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
re_port = re.compile("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/(\d+)")
for line in fi:
port = re.findall(re_port,line)
ip = re.findall(re_ip,line)
print "PORT is " , port , "ip is " ,ip

Related

Multiple IP addresse PING

The below code works perfectly if the input file ip_file.txt have the following format.
8.8.8.8
www.google.com
www.yahoo.com
www.microsoft.com
But how can I ping the IPs if the input is something like this and write the output same in format.
8.8.8.8, www.google.com
www.yahoo.com,www.microsoft.com
My code is given below:
import subprocess
import threading
import time
import re
timestr = time.strftime("%Y-%m-%d %H%M%S")
timesec = time.strftime("%Y-%m-%d%H:%M:%S")
raw_list = []
def ping(host):
results_file = open("results_bng_" + str(timestr) + ".txt", "a")
p = subprocess.Popen(["ping", host, "-n", "5"], shell=True, universal_newlines=True, stdout=subprocess.PIPE)
response = p.communicate()[0]
for i in response.split("\n"):
para =i.split("=")
# print(para)
try:
if para[0].strip() =="Minimum":
latency =para[3].strip()
print(latency)
latfin = re.findall('\d+', latency)
latfin1 = latfin[0]
except:
print("time run")
if "Received = 1" and "Approximate" in response:
print(f"UP {host} Ping Successful")
results_file.write(f"{host},UP,{latfin1},{timesec}"+ "\n")
else:
print(f"Down {host} Ping Unsuccessful")
results_file.write(f"{host},Down,0,{timesec}" + "\n")
results_file.close()
with open(r'bng.txt', "r") as server_list_file:
hosts = server_list_file.read()
hosts_list =hosts.split('\n')
num_threads = 1
number = 0
while number< len(hosts_list):
# print(number)
for i in range(num_threads):
t = threading.Thread(target=ping, args=(hosts_list[number+i],))
t.start()
t.join()
number = number +1
You could replace each newline character with a comma and split at each comma:
bng.txt:
8.8.8.8, www.google.com
www.yahoo.com,www.microsoft.com
Code:
with open(r'bng.txt', "r") as server_list_file:
hosts = server_list_file.read()
hosts_list = hosts.replace('\n', ',').split(',')
for host in hosts_list:
print(host.strip()) # strip remaining whitespaces
Out:
8.8.8.8
www.google.com
www.yahoo.com
www.microsoft.com
Pings are specific IP packets that can only be sent to one ip at a time. There are special IP which are meant for broadcasting. For example, you could direct your ping at a specific subnet and the devices connected to that subnet could all choose to answer to a ping. Note that most routers or IP stacks do not answer to such broadcast pings nowadays as they could be used to discover the devices that are connected to the subnet.
After you open your file you need to do a for loop and read each line at a time and split based on comma. That will ultimately give you a list of all single IPs / hosts to ping. Something like.
listOfAllIPs = []
for line in file:
x = line.split(',') ## this makes x a list
listOfAllIPs = listOfAllIPs + x
After that runs you should be able to use listOfAllIPs as your input. It will have 1 IP or host per item. Just iterate through.
this will be useful for you
import os
import subprocess
list = []
with open('./ip.txt', 'r') as f:
ip = f.read().split(',')
list.append(ip)
for i in range(len(list[0])):
ip = list[0][i]
print(30*'-')
if subprocess.Popen(["ping", "-n", "1", "-w", "200", ip], shell=True).wait() == 1: print('active', ip)
else: print('inactive', ip)

Python - Netmiko read from 2 columns

I have the following code that reads a CSV with a list of hostnames, and runs 2 commands.
I need to change this so that the CSV file it receives has 2 columns, one with the hostname, and another with the corresponding command to be inserted in that router.
Hostname
Comand
CPE_1111
sh ip int br
CPE_2222
sh run
etc
(...)
(...)
nodenum=1
f=open('routers.csv', 'r') #File with Hostnames
c=f.read()
file_as_list = c.splitlines()
with open('Output.txt','w') as f: #File with output
logf = open("error.csv", "a") #Logfile
loga = csv.writer(logf)
loga.writerow(["Hostname"])
for i in file_as_list :
print ("Node", nodenum, "...Checking IP Address...", i)
try:
Connection = netmiko.ConnectHandler(ip=i, device_type="cisco_ios" , username=raw_input("Enter your Username:"), password=getpass.getpass(), verbose=False)
except:
try:
print("Cannot connect via SSH. Trying Telnet")
Connection = netmiko.ConnectHandler(ip=i, device_type="cisco_ios_telnet" , username=raw_input("Enter your Username:"), password=getpass.getpass(), verbose=False)
except:
print("SSH and Telnet Failed")
print("")
now = str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
loga.writerow([i])
nodenum = nodenum+1
continue
hostname = (Connection.send_command("show run | include hostname"))
cellular = (Connection.send_command("sh ip int brief"))
Connection.disconnect
(...)
Your answer lies with how the csv is read. You can use csv.DictReader() to read each row and convert it to a dictionary.
import csv
with open(file="routers.csv", mode="rt") as f:
next(f)
lst = csv.DictReader(f=f, fieldnames=["ip", "cmd"])
ips_cmds = list(lst)
for ip_cmd in ips_cmds:
print("Hostname:", ip_cmd["ip"])
print("Command:", ip_cmd["cmd"], end="\n\n")
# Hostname: CPE_1111
# Command: show ip interface brief
# Hostname: CPE_2222
# Command: show running-config
Then in the for loop where you connect to each router, you can select the value you need from the keys specified in fieldnames.
conn = ConnectHandler(
device_type="cisco_ios",
ip=ip_cmd["ip"],
username=input("Username: "),
password=getpass(prompt="Password: "),
secret=getpass(prompt="Enable Secret: "),
fast_cli=False,
)
hostname = conn.send_command(command_string=ip_cmd["cmd"])
Don't forget to add the parentheses for disconnect() function to be executed.
conn.disconnect()

Read from csv and check the ip address reachability

I am reading the IP addresses from a CSV and then check if the IP addresses are reachable store the IP addresses in the list, please advise what is it that I am doing here is wrong?
addr = []
def ip_reachable(addr):
result = subprocess.run(f"ping -n 3 -w 1 {addr}", stdout=subprocess.DEVNULL)
if result.returncode == 0:
return result.returncode, addr
with open("test.csv") as file_name:
read_csv_file = csv.DictReader(file_name)
for index_col in read_csv_file:
if ip_reachable(index_col["column_1"]):
addr.append(ip_reachable)
print(addr)
Instead of:
addr.append(ip_reachable)
Try this:
addr.append(index_col['column_1'])
I believe you want to store the address itself i.e. in column1 and not the method ip_reachable.

How to read list of ip address from a text file and print it out

*I want to print out ip addresses from textfile (solved)
****no ip address in the textfile and error message will be shown.** (solved)
I have attached my current codes at the bottom, can any one please help?**
**
****IP addresses in the textfile will look like this.****
**
192.168.12.1
192.168.12.28
*****And the following is my current codes...*****
f=open('output.txt','r')
print "IP address is ", f.read()
f.close()
Use file.readlines() inside a loop.
So, the Code will be:
f=open('output2.txt','r')
c=f.readlines()
for i in c :
print ("IP address of attacker is ", i)
f.close()
Get IP address from text file and check. See my code on git.
import socket
import re
f = open('ip_list.txt', 'r') #Text file with many ip address
o = f.read()
ip1 = re.findall( r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", o )
hosts = ip1
ports = [80]
for host in hosts:
for port in ports:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
result = s.connect_ex((host, port))
if result == 0:
print(" [*] Port " + str(port) + " open!" + host)
else: print("[+] CLOSE HOST " + host + ":" + str(port))
except:
pass
It is best to open the file in its own context with 'with'. This way it will be closed automatically after the last line has been reached. Then loop trough the lines and add your text before each line. Another upside of this solution is that you do not have to keep all IPs in memory. The IPs will be streamed one at a time.
This code will also print a message if no ip was found.
with open('output2.txt','r') as f:
ip_not_found = True
for line in f:
ip_not_found = False
print "IP address of attacker is {IP}".format(IP=line)
if ip_not_found:
print 'no ip address was found'
import sys
import os
import time
b='sudo tshark -i ens33 -Y "tcp contains "attack"" -T fields -e ip.src -a duration:20>output2.txt'
a=os.popen(b)
time.sleep(22)
with open(output2.txt,"r") as f:
ip=f.read.split('\n')
for Ip in ip:
print "IP address of attacker is ", Ip
You have to just split the contents of the file at every newline.
import ipaddress
ip_address_file = open('ip.txt', 'r') # open text file with ip addresses
for i in ip_address_file: # loop through the ip text file
i = i.strip() # read each line
try:
i = ipaddress.ip_address(str(i)) #validates either ip is ipv4 or 6
except ValueError: #catch error for invalid ip format
print('invalid ip '.format(i))
continue # if line empty continue with loop

python search string from socket

I have the following text file:
ADDRESS1 192.168.124.1
ADDRESS2 192.168.124.2
ADDRESS3 192.168.124.3
And I wrote the following string server in python (strsrv.py) :
#!/usr/bin/env python
import socket
import sys
host = ''
port = 50000
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(backlog)
while 1:
global f
client, address = s.accept()
data = client.recv(size)
with open('list.txt', 'r') as my_file:
for f in my_file.readlines():
if(f.find('%s' % data)>-1):
data = f
if f:
client.send(data)
client.send(f)
client.close()
I'm trying to connect to this server sending a string. This string must match one of lines described on text file. Ex: sending 'ADDRESS1' should return 'ADDRESS1 192.168.124.1' from the server, but it doesn't works. Any string sent returns only the last line of the text file. Please could someone point me to the right direction? Thanks :)
How are you testing this? Assuming you open a socket and connect to the host you should see that you are in fact receiving the correct line as well as the last one. Why? Because in the for loop you keep changing the value of f, the last value of f will be the last line in the file, and you send it back after sending data (which at that point is the correct value).
Here's a suggestion for how you might modify your code (assuming you want the full line back and you dont want wildcarding):
#!/usr/bin/env python
import socket
import sys
host = ''
port = 50000
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(backlog)
# build dict of addresses first, no need to do this for each message
with open('list.txt', 'r') as my_file:
address_map = dict(line.split() for line in my_file)
while True:
client, address = s.accept()
req_address = client.recv(size)
ip = address_map.get(req_address, 'Not found')
client.send(req_address + ' ' + ip)
client.close()
You can simply test this by doing this while the above is running:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('', 50000))
s.send('ADDRESS2')
s.recv(1024)

Categories