Python - PING a list of IP Address from database - python

Python - PING a list of IP Address from database
I have a list of ip addresses consisting of 200 locations, which in that location there are 4 ip addresses that I need to do ping testing. I intend to make a command which when I write the name or code of a particular location then it will directly ping to 4 ip address at that location. I have learned a bit to create a list that contains the ip address I entered through the command input () like this :
import os
import socket
ip = []
y = ['IP 1 : ','IP 2 : ', 'IP 3 : ', 'IP 4 : ']
while True:
for x in y:
server_ip = input(x)
ip.append(server_ip)
break
for x in ip:
print("\n")
rep = os.system('ping ' + x + " -c 3")
please give me a little advice about the command I want to make so that I no longer need to enter the ip address one by one. which still makes me confused, especially on how to make the existing items in the database into a variable x which we will insert into this command;
rep = os.system ('ping' + x + "-c 3")

EDIT: It now iterates over a CSV file rather than a hard-coded Python dictionary.
I believe you will be better off using python dictionaries rather than python lists. Assuming you are using Python 3.X, this is what you want to run:
import os
import csv
# Save the IPs you want to ping inside YOURFILE.csv
# Then iterate over the CSV rows using a For Loop
# Ensure your ip addresses are under a column titled ip_address
with open('YOURFILE.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
rep = os.system("ping " + row['ip_address'] + " -c 3")

Related

Program to extract valid ips and valid ftp addresses

i'm still pretty new in programming. I'm trying to write a code that can find all valid IP addresses and all ftp addresses in a text file and write only those addresses to an other text file. The informations i'm trying to extract are in a pretty big and unsorted file. Here's a few lines of that file without going crazy:
1331903561.260000 CptK3340W66OKHK3Rd 192.168.202.96 43740 192.168.28.103 21 <unknown>
1331905499.220000 Cup8D83JUM166udWb 192.168.202.102 4379 192.168.21.101 21 ftp password#example.com DELE ftp://192.168.21.101/.cache/ - 550 /.cache/.ftpduBnga4: Operation not permitted - - - - -
1331905499.220000 Cup8D83JUM166udWb 192.168.202.102 4379 192.168.21.101 21 ftp password#example.com PASV - - - 227 Entering Passive Mode (192,168,21,101,189,111). T 192.168.202.102 192.168.21.101 48495
The code I have gives me the informations I need but I am wondering if I can make my output more clean. My output gives me every ip in 1 line seperated with a comma. I would like to have 1 IP per line to make looking at it easier.
import os
from os import chdir
import re
import socket
chdir("filepath")
x= open('filepath')
fichip = open('ip.txt', 'w', encoding='utf8')
fichftp = open('ftp.txt', 'w', encoding='utf8')
ipvalide = r"(?:2(?:5[0-5]|[0-4][0-9])|[0-1]?[0-9]{1,2})(?:\.(?:2(?:5[0-5]|[0-4][0-9])|[0-1]?[0-9]{1,2})){3}"
ftpvalide = r"ftp:\/\/(?:2(?:5[0-5]|[0-4][0-9])|[0-1]?[0-9]{1,2})(?:\.(?:2(?:5[0-5]|[0-4][0-9])|[0-1]?[0-9]{1,2})){3}" #(ftp:\/\/)
txt = x.readlines()
ipmatch = re.findall(ipvalide, str(txt))
ftpmatch = re.findall(ftpvalide, str(txt))
in_listip = set(ipmatch) #not to have any duplicates ip
in_listftp = set(ftpmatch)#not to have any duplicates ftp
fichip.write(str(in_listip))
fichftp.write(str(in_listftp))
fichip.close()
fichftp.close()
x.close()

python nesting loops

I am trying perform a nested loop to combine data into a line by using matched MAC Addresses in both files.
I am able to pull the loop fine without the regex, however, when using the search regex below, it will only loop through the MAC_Lines once and print the correct results using the first entry in the MAC_Lines and stop. I'm unsure how to make the MAC_Lines go to the next line and repeat the process for all of the entries in the MAC_Lines.
try:
for mac in MAC_Lines:
MAC_address = re.search(r'([a-fA-F0-9]{2}[:|\-]?){6}', mac, re.I)
MAC_address_final = MAC_address.group()
for arp in ARP_Lines:
ARP_address = re.search(r'([a-fA-F0-9]{2}[:|\-]?){6}', arp, re.I)
ARP_address_final = ARP_address.group()
if MAC_address_final == ARP_address_final:
print mac + arp
continue
except Exception:
print 'completed.'
Results:
13,64,00:0c:29:36:9f:02,giga-swx 0/213,172.20.13.70, 00:0c:29:36:9f:02, vlan 64
completed.
I learned that the issue was how I opened the file. I should have used the 'open':'as' keywords when opening both files to allow the files to properly close and reopen for the next loop. Below is the code I was looking for.
Below is the code:
with open('MAC_List.txt', 'r') as read0:for items0 in read0:
MAC_address = re.search(r'([a-fA-F0-9]{2}[:|\-]?){6}', items0, re.I)
if MAC_address:
mac_addy = MAC_address.group().upper()
with open('ARP_List.txt', 'r') as read1:
for items1 in read1:
ARP_address = re.search(r'([a-fA-F0-9]{2}[:|\-]?){6}', items1, re.I)
if ARP_address:
arp_addy = ARP_address.group()
if mac_addy == arp_addy:
print(items0.strip() + ' ' + items1.strip())

Create multiple files based on user input in python

i am new to python and I've written a code which create configuration files for my application. I've created the code which works for 2 IP's but it may happen that user may input more IP's and for each increase in Ip the config file will be changed. There are authentication servers and they can be either 1 or 2 only.
I am passing input to python code by a file name "inputfile", below is how it look like:
EnterIp_list: ip_1 ip_2
authentication_server: as_1 as_2
Below is how the final configuration files are created:
configfile1: configfile2:
App_ip: ip_1 App_ip: ip_2
app_number: 1 app_number: 2
authen_server: as_1 authen_server: as_2
Below is how python3 code looks:
def createconfig(filename, app_ip, app_number, authen_server)
with open(filename, 'w') as inf:
inf.write("App_ip=" + app_ip + "\n")
inf.write("app_numbber=" + app_number)
inf.write("authen_server="+ authen_server)
with open("inputfile") as f:
for line in f:
if EnterIP_list in line:
a= line.split("=")
b = a[1].split()
if authentiation_server in line:
c= line.split("=")
d=c[1].split()
createconfig(configfile1, b[0], 1, d[0])
createconfig(configfile2, b[1], 2, d[1])
Users has freedom to input as many IP's as they wish for. Can someone please suggest what need to be done to make code more generic and robust so that it will work for any number of input ip's ??? also value for app_number increases with each new ip added.
There will always be two authentication server and they go in round robin e.g. the third app ip will be associated to "as_1" again.
You just need to iterate over your ip list in b, be aware that your current code only works for the last line of your "inputfile". As long as there is only one line, thats ok.
with open("inputfile") as f:
for line in f:
a= line.split("=")
b = a[1].split()
app_count = 1
for ip in b:
createconfig("configfile%s" % app_count , ip, app_count)
app_count += 1
Edit: Solution updated regarding your code change.
with open("inputfile") as f:
for line in f:
if EnterIP_list in line:
ips = line.split("=")[1].split()
if authentiation_server in line:
auth_servers = line.split("=")[1].split()
app_count = 1
for ip, auth_server in zip(ips, auth_servers):
createconfig("configfile%s" % app_count , ip, app_count, auth_server)
app_count += 1
A not so great way of doing it without modifying so much of your code would be to remove the last two createconfig() calls and instead do it in a loop once you have b as follows:
with open("inputfile") as f:
for line in f:
a= line.split("=")
b = a[1].split()
for app_number in b:
createconfig("configfile{}".format(app_number), b[app_number], app_number)

using dig with python to list all host

I'm very newbie with python and programming and I just can't find the way to do the code I need. So help, please :)
Background:
I'll be checking multiple different (linux) environments so I want to get the nameserver (ns) and domain information from resolv.conf and pass these values to dig.
Thanks to this forum and google I was able to get the ns and domain info but struggling still how to pass the info to dig.
Python version is 2.7.
Linux is rhel6.x.
Problem:
How to format the dig command using return values for ns and domain and giving few parameters:
dig +search <domain>. axfr #<ns> +noall +answer
The and are coming from the functions.
What I want:
read the ns and domain from /et/resolv.conf. Only first ns is needed
(this has been achieved)
pass the ns and domain to dig (this is the part I just can't figure out). dig command is this: dig +search . axfr # +noall +answer
modify the output of dig so that the list would like this:
host_ip1 host_name1
host_ip2 host_name2
....
would be nice if the output was sorted based on IP
that's about it.
I know there are dns modules available to do the same, but they are no option for me since they are not available.
So far this is what I have:
# -*- coding: utf-8 -*-
### Functions start ###
def get_ns():
with open("/etc/resolv.conf","r") as readFile:
#print [line.split(" ")[1].strip() for line in readFile.readlines() if line.startswith("nameserver")][0]
x = [line.split(" ")[1].strip() for line in readFile.readlines() if line.startswith("nameserver")][0]
readFile.close()
return x
def get_domain():
with open("/etc/resolv.conf","r") as readFile:
#print [line.split(" ")[1].strip() for line in readFile.readlines() if line.startswith("search")][0]
y = [line.split(" ")[1].strip() for line in readFile.readlines() if line.startswith("search")][0]
readFile.close()
return y
### Functions end ###
# just to test all is working:
ns = get_ns()
# to get the dig command:
domain = get_domain()
domain1 = domain + '.'
ns1 = '#' + ns
print ns1
print domain1
list = os.system("dig +search " + domain1 + " axfr " + ns1 + " +noall +answer")
print list
Any help will be highly appreciated!

How to store scapy packet data?

I have a DNS packet sniffer built with Scapy that I'd like to store packet data from.
I understand that packet data is stored as a dictionary, which should make it ideal to store in another dictionary or array. I can see using pkt[0].summary that the data is correct and I am getting packets but I cannot figure out how to correctly store it.
As I am new to Python / Scapy, my question is how to store / append this packet data to a dictionary or array as the packets come through.
This is what the code looks like:
#!/usr/bin/env python
from scapy.all import *
from datetime import datetime
import time
import datetime
import sys
# Select interface and ports of interest
interface = 'ens33'
bpf = 'udp and port 53'
# SELECT/FILTER MSGS
def select_DNS(pkt):
pkt_time = pkt.sprintf('%sent.time%')
# SELECT/FILTER DNS MSGS
try:
dict = []
# queries
if DNSQR in pkt and pkt.dport == 53:
domain = pkt.getlayer(DNS).qd.qname.decode() # .decode() gets rid of the b''
print('Q - Time: ' + pkt_time + ' , source IP: ' + pkt[IP].src + ' , domain: ' + domain)
# responses
elif DNSRR in pkt and pkt.sport == 53:
domain = pkt.getlayer(DNS).qd.qname.decode()
print('R - Time: ' + pkt_time + ' , source IP: ' + pkt[IP].src + ' , domain: ' + domain)
except:
pass
# START SNIFFER
sniff(iface=interface, filter=bpf, store=0, prn=select_DNS)
I'm fairly sure the packet structure is not a dictionary, even though it provides some dictionary like features (overriding the slicing notation).
If you want to store the packets in a list (array), just append them as you go.
cache = []
def select_DNS(pkt):
cache.append(pkt)
If you want to store packets to disk, I would suggest writing them out using the wrpacp function to save them in "pcap" format.
wrpcap("temp.cap",pkts)

Categories

Resources