本文整理汇总了Python中netmiko.ConnectHandler.disconnect方法的典型用法代码示例。如果您正苦于以下问题:Python ConnectHandler.disconnect方法的具体用法?Python ConnectHandler.disconnect怎么用?Python ConnectHandler.disconnect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类netmiko.ConnectHandler
的用法示例。
在下文中一共展示了ConnectHandler.disconnect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from netmiko import ConnectHandler [as 别名]
# 或者: from netmiko.ConnectHandler import disconnect [as 别名]
def main():
router = {
'device_type': 'cisco_ios',
'ip': '10.9.0.67',
'username': 'myuser',
'password': 'mypass'
}
# Connect to device
device_conn = ConnectHandler(**router)
# Show logging buffered
print "Pre Change Logging Check:"
print device_conn.send_command("show run | in logging")
# To change the logging buffered value
config_commands = ['logging buffered 25000', 'do wr mem']
output = device_conn.send_config_set(config_commands)
print output
# Show logging buffered
print "Post Change Logging Check:"
print device_conn.send_command("show run | in logging")
# Close connection
device_conn.disconnect()
示例2: setup_module
# 需要导入模块: from netmiko import ConnectHandler [as 别名]
# 或者: from netmiko.ConnectHandler import disconnect [as 别名]
def setup_module(module):
module.EXPECTED_RESPONSES = {
'enable_prompt' : 'n7k1#',
'base_prompt' : 'n7k1',
'interface_ip' : '10.3.3.245',
'config_mode' : '(config)'
}
show_ver_command = 'show version'
module.basic_command = 'show ip int brief'
net_connect = ConnectHandler(**cisco_nxos)
module.show_version = net_connect.send_command(show_ver_command)
module.show_ip = net_connect.send_command(module.basic_command)
net_connect.enable()
module.enable_prompt = net_connect.find_prompt()
module.config_mode = net_connect.config_mode()
config_commands = ['logging monitor 3', 'logging monitor 7', 'no logging console']
net_connect.send_config_set(config_commands)
module.exit_config_mode = net_connect.exit_config_mode()
module.config_commands_output = net_connect.send_command("show run | inc 'logging monitor'")
net_connect.disconnect()
示例3: main
# 需要导入模块: from netmiko import ConnectHandler [as 别名]
# 或者: from netmiko.ConnectHandler import disconnect [as 别名]
def main():
'''
This will run an command via serial on an cisco ios switch and so
serial cable must be attached to the device
'''
serialhandle = {
'device_type':'cisco_ios_serial',
'port': 'USB Serial', # can be COM<number> or any line you can get from
# serial.tools.list_ports.comports()
'username':'<username>',
'password':'<password>',
'secret':'<secret>',
'serial_settings':{ # this are the default values
'baudrate': 9600,
'bytesize': serial.EIGHTBITS,
'parity': serial.PARITY_NONE,
'stopbits': serial.STOPBITS_ONE
}
}
net_connect = ConnectHandler(**serialhandle)
net_connect.enable()
output = net_connect.send_command('show run')
net_connect.disconnect()
print(output)
示例4: setup_module
# 需要导入模块: from netmiko import ConnectHandler [as 别名]
# 或者: from netmiko.ConnectHandler import disconnect [as 别名]
def setup_module(module):
module.EXPECTED_RESPONSES = {
'base_prompt' : 'openstack-rb5',
'config_mode' : '(config)',
}
net_connect = ConnectHandler(**brocade_vdx)
# Enter enable mode
module.prompt_initial = net_connect.find_prompt()
net_connect.enable()
module.enable_prompt = net_connect.find_prompt()
# Send a set of config commands
module.config_mode = net_connect.config_mode()
config_commands = ['logging raslog console WARNING', 'interface vlan 20', 'banner motd test_message']
net_connect.send_config_set(config_commands)
# Exit config mode
module.exit_config_mode = net_connect.exit_config_mode()
# Verify config changes
module.config_commands_output = net_connect.send_command('show vlan brief')
net_connect.disconnect()
示例5: main
# 需要导入模块: from netmiko import ConnectHandler [as 别名]
# 或者: from netmiko.ConnectHandler import disconnect [as 别名]
def main():
"""
This will run an command via serial on an cisco ios switch and so
serial cable must be attached to the device
"""
serialhandle = {
"device_type": "cisco_ios_serial",
"port": "USB Serial", # can be COM<number> or any line you can get from
# serial.tools.list_ports.comports()
"username": "<username>",
"password": "<password>",
"secret": "<secret>",
"serial_settings": { # this are the default values
"baudrate": 9600,
"bytesize": serial.EIGHTBITS,
"parity": serial.PARITY_NONE,
"stopbits": serial.STOPBITS_ONE,
},
}
net_connect = ConnectHandler(**serialhandle)
net_connect.enable()
output = net_connect.send_command("show run")
net_connect.disconnect()
print(output)
示例6: main
# 需要导入模块: from netmiko import ConnectHandler [as 别名]
# 或者: from netmiko.ConnectHandler import disconnect [as 别名]
def main():
router1 = {
'device_type': 'cisco_ios',
'ip': '10.9.0.67',
'username': 'myuser',
'password': 'mypass'
}
router2 = {
'device_type': 'cisco_ios',
'ip': '10.63.176.57',
'username': 'myuser',
'password': 'mypass'
}
routers = [router1, router2]
for router in routers:
# Connect to device
device_conn = ConnectHandler(**router)
# Change config from file
device_conn.send_config_from_file(config_file='config_commands.txt')
# Validate changes
print ">>> " + device_conn.find_prompt() + " <<<"
#output = device_conn.send_command("show run | in logging", delay_factor=.5)
output = device_conn.send_command_expect("show run | in logging")
print output + "\n\n"
# Close connection
device_conn.disconnect()
示例7: login
# 需要导入模块: from netmiko import ConnectHandler [as 别名]
# 或者: from netmiko.ConnectHandler import disconnect [as 别名]
class ConnectivityTest:
def login(self):
self.cisco_switch = ConnectHandler(
device_type='cisco_nxos',
ip=HOSTNAME,
username=USERNAME,
password=PASSWORD,
verbose=False)
def setUp(self):
self.failure = False
self.login()
self.cisco_switch.send_command('checkpoint ' + CHECKPOINT_NAME)
def test_snippets(self):
for snippet_file in os.listdir(SNIPPET_DIR):
self.cisco_switch.send_config_from_file(os.path.join(SNIPPET_DIR, snippet_file))
ping_result = self.cisco_switch.send_command('ping 192.168.56.2')
print "=========================="
print snippet_file
print "--------------------------"
print ping_result
if not ping_is_successful(ping_result):
self.failure = True
def tearDown(self):
self.cisco_switch.send_command('rollback running-config checkpoint ' + CHECKPOINT_NAME)
self.cisco_switch.send_command('no checkpoint ' + CHECKPOINT_NAME)
self.cisco_switch.disconnect()
示例8: get_cdp_neighbor_details
# 需要导入模块: from netmiko import ConnectHandler [as 别名]
# 或者: from netmiko.ConnectHandler import disconnect [as 别名]
def get_cdp_neighbor_details(ip, username, password, enable_secret):
"""
get the CDP neighbor detail from the device using SSH
:param ip: IP address of the device
:param username: username used for the authentication
:param password: password used for the authentication
:param enable_secret: enable secret
:return:
"""
# establish a connection to the device
ssh_connection = ConnectHandler(
device_type='cisco_ios',
ip=ip,
username=username,
password=password,
secret=enable_secret
)
# enter enable mode
ssh_connection.enable()
# prepend the command prompt to the result (used to identify the local device)
result = ssh_connection.find_prompt() + "\n"
# execute the show cdp neighbor detail command
# we increase the delay_factor for this command, because it take some time if many devices are seen by CDP
result += ssh_connection.send_command("show cdp neighbor detail", delay_factor=2)
# close SSH connection
ssh_connection.disconnect()
return result
示例9: main
# 需要导入模块: from netmiko import ConnectHandler [as 别名]
# 或者: from netmiko.ConnectHandler import disconnect [as 别名]
def main():
router1 = {
'device_type': 'cisco_ios',
'ip': '10.9.0.67',
'username': 'myuser',
'password': 'mypass'
}
router2 = {
'device_type': 'cisco_ios',
'ip': '10.63.176.57',
'username': 'myuser',
'password': 'mypass'
}
routers = [router1, router2]
for router in routers:
# Connect to device
device_conn = ConnectHandler(**router)
# Print arp table
print device_conn.send_command("show arp")
print "\n\n"
# Close connection
device_conn.disconnect()
示例10: setup_module
# 需要导入模块: from netmiko import ConnectHandler [as 别名]
# 或者: from netmiko.ConnectHandler import disconnect [as 别名]
def setup_module(module):
module.EXPECTED_RESPONSES = {
'enable_prompt' : 'xe-test-rtr#',
'base_prompt' : 'xe-test-rtr',
'interface_ip' : '172.30.0.167',
'config_mode' : '(config)',
}
show_ver_command = 'show version'
module.basic_command = 'show ip int brief'
net_connect = ConnectHandler(**cisco_xe)
module.show_version = net_connect.send_command(show_ver_command)
module.show_ip = net_connect.send_command(module.basic_command)
net_connect.enable()
module.enable_prompt = net_connect.find_prompt()
module.config_mode = net_connect.config_mode()
config_commands = ['logging buffered 20000', 'logging buffered 20010', 'no logging console']
net_connect.send_config_set(config_commands)
module.exit_config_mode = net_connect.exit_config_mode()
module.config_commands_output = net_connect.send_command('show run | inc logging buffer')
net_connect.disconnect()
示例11: clean_unused_files
# 需要导入模块: from netmiko import ConnectHandler [as 别名]
# 或者: from netmiko.ConnectHandler import disconnect [as 别名]
def clean_unused_files(self):
# Initiate SSH Connection to device
device = {'device_type': 'cisco_ios',
'ip': self.ip_address,
'username': self.username,
'password': self.password}
ssh_conn = ConnectHandler(**device)
# Loop through the inactive images of the device and attempt to delete.
for image in self.inactive_images:
# Perform a dir to determine if the image exists, to avoid an "image not found" command error.
dir_output = ssh_conn.send_command('dir')
if image in dir_output and image != self.compliant_image:
try:
# Force delete the inactive image from flash. i.e. 'del /force flash:/image.bin'. Allows for different file systems (flash:, slot0:, etc)
ssh_conn.send_command('del /force {}/{}'.format(self.filesystem, image))
print "Deleted image file %s from %s" % (image, self.hostname)
self.inactive_images.remove(image)
except Exception as e:
print "Error - %s" % e
else:
# If file no longer exists (perhaps deleted manually), update the inactive_images list.
print "Image %s not found or filename matches the compliant image for model %s, skipping...." % (image,self.model)
self.inactive_images.remove(image)
ssh_conn.disconnect()
示例12: main
# 需要导入模块: from netmiko import ConnectHandler [as 别名]
# 或者: from netmiko.ConnectHandler import disconnect [as 别名]
def main():
inputfile, config_commands = get_cmd_line()
print("Switch configuration updater. Please provide login information.\n")
# Get username and password information.
username = input("Username: ")
password = getpass("Password: ")
enasecret = getpass("Enable Secret: ")
print("{}{:<20}{:<40}{:<20}".format(
"\n", "IP Address", "Name", "Results"), end="")
for switchip in inputfile:
ciscosw = {
"device_type": "cisco_ios",
"ip": switchip.strip(),
"username": username.strip(),
"password": password.strip(),
"secret": enasecret.strip(),
}
print()
print("{:<20}".format(switchip.strip()), end="", flush=True)
try:
# Connect to switch and enter enable mode.
net_connect = ConnectHandler(**ciscosw)
except Exception:
print("** Failed to connect.", end="", flush=True)
continue
prompt = net_connect.find_prompt()
# Print out the prompt/hostname of the device
print("{:<40}".format(prompt), end="", flush=True)
try:
# Ensure we are in enable mode and can make changes.
if "#" not in prompt[-1]:
net_connect.enable()
print("#", end="", flush=True)
except Exception:
print("Unable to enter enable mode.", end="", flush=True)
continue
else:
for cmd in config_commands:
# Make requested configuration changes.
try:
if cmd in ("w", "wr"):
output = net_connect.save_config()
print("w", end="", flush=True)
else:
output = net_connect.send_config_set(cmd)
if "Invalid input" in output:
# Unsupported command in this IOS version.
print("Invalid input: ", cmd, end="", flush=True)
print("*", end="", flush=True)
except Exception:
# Command failed! Stop processing further commands.
print("!")
break
net_connect.disconnect()
示例13: cisco_xr
# 需要导入模块: from netmiko import ConnectHandler [as 别名]
# 或者: from netmiko.ConnectHandler import disconnect [as 别名]
def cisco_xr(host):
from netmiko import ConnectHandler
from prettytable import PrettyTable
from modules import ReadableRate
import re
interface, neighbor = "",""
rx,tx = "",""
table = PrettyTable(['Interface','In','Out','Neighbor','Metric','Total_Traffic'])
net_connect = ConnectHandler(**host)
no_prompt = net_connect.send_command("terminal exec prompt no-timestamp")
isis_int = net_connect.send_command("show isis neighbor | include Up")
isis_int = isis_int.splitlines()
while '' in isis_int:
isis_int.pop(isis_int.index(''))
for line in isis_int:
total_traffic = 0
# Extract neighbor and interface
for item in line.split():
if re.search("[0-9]+/[0-9]+/[0-9]+/[0-9+]", item) != None:
interface = item
elif re.search("^BE", item) != None:
interface = 'Bundle-Ether' + item[2:len(item)]
neighbor = line.split()[0]
neighbor = neighbor.replace('-re0','') # Don't care about Junipers with apply-
neighbor = neighbor.replace('-re1','') # groups to append active RE to hostname
# Get interface traffic
show_int = net_connect.send_command("show interface " + interface.split('.')[0] + ' | include "put rate"')
show_int = show_int.splitlines()
for l in show_int:
counter = 0
for thing in l.split():
if re.search("bits",thing) == None:
counter+=1
else:
counter -=1
if "nput" in l:
rx = ReadableRate(int(l.split()[counter]))
total_traffic = total_traffic + int(l.split()[counter])
counter +=1
elif "utput" in l:
tx = ReadableRate(int(l.split()[counter]))
total_traffic = total_traffic + int(l.split()[counter])
counter +=1
# Get isis metric
show_isis = net_connect.send_command("show isis interface " + interface + " | include Metric")
show_isis = show_isis.splitlines()
for lines in show_isis:
for word in lines .split():
if re.search("[0-9]+/[0-9]+", word) != None:
metric = word
table.add_row([interface,rx.rate,tx.rate,neighbor,metric,(total_traffic*-1)])
net_connect.disconnect()
print(table.get_string(sortby='Total_Traffic'))
示例14: connect_ssh
# 需要导入模块: from netmiko import ConnectHandler [as 别名]
# 或者: from netmiko.ConnectHandler import disconnect [as 别名]
def connect_ssh(target_ip, username, password, DEBUG, output):
if DEBUG:
verbose = True
else:
verbose = False
dns_list = list()
for i in target_ip:
try:
# Define variables for function
x, z, v = 0, 1, 2
vlan_list = list()
output += ("*" * 4 + " START device: %s " + "-" * 35 + ">" * 4 + "\n") % i
ssh_con = ConnectHandler(device_type='hp_procurve', ip=i, username=username, password=password,
verbose=verbose)
# Find hostname will be used for first part of VLAN IP dns name
output += "\nFind prompt: \n"
output_cmd = ssh_con.find_prompt()
hostname = output_cmd
if DEBUG: print hostname
output += output_cmd
# Get VLAN information from switch
output_cmd = ssh_con.send_command('show vlan custom id name ipaddr')
vlan_output = output_cmd.split(' ')
output += output_cmd
# Clean output information
vlan_output = filter(None, vlan_output)
# Filter VLAN ID's
for y in vlan_output[18:-1]:
if y != '\n':
vlan_list.append(y)
if DEBUG: print vlan_list
lp = len(vlan_list) / 3
while lp != 0:
vlan_name = hostname[:-1] + '-' + 'VL' + vlan_list[x] + '-' + vlan_list[z]
dns_list.append(vlan_name)
dns_list.append(vlan_list[v])
x += 3
z += 3
v += 3
lp -= 1
if DEBUG: print dns_list
ssh_con.disconnect()
except:
print "Problem connecting with ip: %s" % (i)
continue
return output, dns_list
示例15: connect_silent
# 需要导入模块: from netmiko import ConnectHandler [as 别名]
# 或者: from netmiko.ConnectHandler import disconnect [as 别名]
def connect_silent(*ios_commands,ip_address,dev=0):
# connect_silent is able to log into and run enable mode commands as well but it connects on a best effort basis.
# It might connect to enable mode if the enable secret is correct but it might just connect to user exec if it's not.
# If you want verification about being able to connect to enable mode, use connect_enable_silent.
# connect_silent is recommended for user exec commands.
global output
try:
with open ("credentials.txt") as line:
line = json.load(line)
try_credentials = 0
for k,v in line.items():
router=(k,v)
try_credentials += 1
try:
if globals.pref_cred != {} and try_credentials == 1:
if dev != 0:
print("[[DEV:] Trying Prefered credentials]")
ssh = ConnectHandler(**globals.pref_cred, device_type="cisco_ios", ip=ip_address)
else:
if dev != 0:
print("[[DEV:] Trying Privileged User EXEC credentials '", k, "']", sep="")
ssh = ConnectHandler(**router[1], device_type="cisco_ios", ip=ip_address)
except netmiko.ssh_exception.NetMikoAuthenticationException:
if dev != 0:
print ("[[DEV:] Incorrect credentials]")
continue
except netmiko.ssh_exception.NetMikoTimeoutException:
if dev != 0:
print("[[DEV:] SSH not enabled (User EXEC timed out)]")
raise SSHnotEnabled("SSH not enabled on target device (" + ip_address + ")") from None
except Exception:
if dev != 0:
print("[[DEV:] Unknown error in ssh.connect_silent]")
raise UnknownError ("Unknown error in ssh.connect_silent")
else:
for ios_command in ios_commands:
if dev != 0:
print("[[DEV:] Running command '", ios_command, "']", sep="")
output = ios_command + "\n" + ssh.send_command(ios_command)
if dev != 0 and "at '^' marker" in output:
print("[[DEV:] '", ios_command, "' incorrect syntax or requires Privileged EXEC mode]", sep="")
if "at '^' marker" not in output:
ssh.disconnect()
break
if "at '^' marker" in output:
raise IosSyntaxError ("incorrect syntax or requires Privileged EXEC mode")
if globals.pref_cred == {} or globals.pref_cred != {} and try_credentials > 1:
if dev != 0:
print("[[DEV:] Saving '", k, "' as prefered credentials]", sep="")
globals.pref_cred = v
return output
except json.decoder.JSONDecodeError:
if dev != 0:
print("[[DEV:] credentials file not in JSON format]")
raise JsonIncorrectFormat ("Credentials file not in JSON format")