def main(): ''' SCP transfer cisco_logging.txt to network device Use ssh_conn as ssh channel into network device scp_conn must be closed after file transfer ''' ssh_conn = ConnectHandler(**cisco_881) scp_conn = SCPConn(ssh_conn) s_file = 'cisco_logging.txt' d_file = 'cisco_logging.txt' print "\n\n" scp_conn.scp_transfer_file(s_file, d_file) scp_conn.close() output = ssh_conn.send_command("show flash: | inc cisco_logging") print ">> " + output + '\n' # Disable file copy confirmation output = ssh_conn.send_config_set(["file prompt quiet"]) # Execute config merge print "Performing config merge\n" output = ssh_conn.send_command("copy flash:cisco_logging.txt running-config") # Verify change print "Verifying logging buffer change" output = ssh_conn.send_command("show run | inc logging buffer") print ">> " + output + '\n' # Restore copy confirmation output = ssh_conn.send_config_set(["file prompt alert"])
def scp_put_file(self, source_file=None, dest_file=None): """Put file using SCP.""" try: scp = SCPConn(ssh_conn=self) scp.scp_put_file(source_file=source_file, dest_file=dest_file) except Exception: raise finally: scp.close()
def load_file(self, file, dst_file=None): if not dst_file: dst_file = file scp_status = self.ssh.send_command( 'show running-config | i "ip scp server enable"') if not scp_status: self.enable_scp() scp = SCPConn(self.ssh) scp.scp_transfer_file(file, dst_file) scp.close() if not scp_status: self.disable_scp()
def main(): ''' Ansible module to transfer files to Cisco IOS devices. ''' module = AnsibleModule( argument_spec=dict( host=dict(required=True), port=dict(default=22, required=False), username=dict(required=True), password=dict(required=True), source_file=dict(required=True), dest_file=dict(required=True), dest_file_system=dict(required=False), ) ) net_device = { 'device_type': 'cisco_ios', 'ip': module.params['host'], 'username': module.params['username'], 'password': module.params['password'], 'port': int(module.params['port']), 'verbose': False, } ssh_conn = ConnectHandler(**net_device) output = ssh_conn.send_command("show flash: | inc cisco_logging") scp_conn = SCPConn(ssh_conn) source_file = module.params['source_file'] source_md5 = file_md5(source_file) dest_file = module.params['dest_file'] scp_conn.scp_transfer_file(source_file, dest_file) scp_conn.close() output2 = ssh_conn.send_command("show flash: | inc cisco_logging") remote_md5_cmd = "verify /md5 {0}".format(dest_file) dest_md5 = ssh_conn.send_command(remote_md5_cmd) dest_md5 = process_cisco_md5(dest_md5) if source_md5 != dest_md5: module.fail_json(msg="File transferred to Cisco device, but MD5 does not match" \ " source file") module.exit_json(msg="Testing...", changed=True, output=output, source_file=source_file, output2=output2, source_md5=source_md5, dest_md5=dest_md5)
def main(self): ssh_conn = ConnectHandler( device_type='cisco_ios', ip = self.ip, username = self.username, password = self.password ) config_commands = self.cmdlist output = ssh_conn.send_config_set(config_commands) print(output) for f in myfile: s_file = f d_file = f scp_conn = SCPConn(ssh_conn) scp_conn.scp_transfer_file(s_file, d_file) scp_conn.close()
def main(self): ssh_conn = ConnectHandler(device_type='cisco_ios', ip=self.ip, username=self.username, password=self.password) static = os.chdir( '/Users/shaun/dev/netmiko_django/netmiko_django/static/') myfile = os.listdir(static) for f in myfile: s_file = f d_file = f scp_conn = SCPConn(ssh_conn) scp_conn.scp_transfer_file(s_file, d_file) config_commands = self.cmdlist output = ssh_conn.send_config_set(config_commands) print(output) return output scp_conn.close()
def main(self): ssh_conn = ConnectHandler(device_type='cisco_asa', ip=self.ip, username=self.username, password=self.password) static = os.chdir( 'C:\\Users\corcoras\\Desktop\\FY14 INSTALLS\\PythonMotors\\netmiko_django\\netmiko_django\\static' ) myfile = os.listdir(static) for f in myfile: s_file = f d_file = f scp_conn = SCPConn(ssh_conn) scp_conn.scp_transfer_file(s_file, d_file) config_commands = self.cmdlist output = ssh_conn.send_config_set(config_commands) print(output) return output scp_conn.close()
def sendFileToMachine(host: machine.Machine, source_file, dest_file): net_device = { 'device_type': 'linux', 'ip': host.ip, 'username': host.username, 'password': host.password, } try: ssh_conn = ConnectHandler(**net_device) scp_conn = SCPConn(ssh_conn) putFileState = scp_conn.scp_put_file(source_file, dest_file) scp_conn.close() ssh_conn.disconnect() host.status = 2 # Passed return True # succeeded sending the file to machine except: print(f"Failed connect to {host.ip}") host.status = 0 # Failed return False # Filed sending the file to machine
def main(self): ssh_conn = ConnectHandler(device_type='cisco_ios', ip=self.ip, username=self.username, password=self.password) static = os.chdir('C:\\Users\\corcoras\\netmiko_django\\hold') print(static) myfile = os.listdir(static) print(myfile) for f in myfile: if f == 'desktop.ini': pass else: print(f) s_file = f d_file = f scp_conn = SCPConn(ssh_conn) scp_conn.scp_transfer_file(s_file, d_file) config_commands = self.cmdlist output = ssh_conn.send_config_set(config_commands) print(output) return output scp_conn.close()
} # open file containing commands with open('commands.txt') as f: commands_list = f.read().splitlines() # Establish ssh session to device and send commands net_connect = ConnectHandler(**netscaler_device) net_connect.send_config_set(commands_list, delay_factor=4) # open secure copy protocol to transfer backup file to server ssh_conn = ConnectHandler(**netscaler_device) scp_conn = SCPConn(ssh_conn) s_file = '/var/ns_sys_backup/backupfile.tgz' d_file = '/usr/backups/backupfile.tgz' scp_conn.scp_get_file(s_file, d_file) # Close secure copy protocol session scp_conn.close() # Close ssh session net_connect.disconnect() timestr = time.strftime("%Y%m%d-%H%M%S") # Rename backup file to contain time and date stamp os.rename("/usr/backups/backupfile.tgz", "/usr/backups/backupfile.tgz" + timestr)
class BaseNode(object): def __init__(self,created_at,created_by,domain_name,hardware_vendor,lifecycle_status,location_name,mgmt_ip4,mgmt_con_ip4,mgmt_oob_ip4,mgmt_snmp_community4,name,platform_name,oncall_team,opersys,software_image,software_version,type,role_name,serial_num,status,updated_at,updated_by): self.created_at = created_at self.created_by = created_by self.domain_name = domain_name self.hardware_vendor = hardware_vendor self.lifecycle_status = lifecycle_status self.location_name = location_name self.mgmt_con_ip4 = mgmt_con_ip4 self.mgmt_ip4 = mgmt_ip4 self.mgmt_oob_ip4 = mgmt_oob_ip4 self.mgmt_snmp_community4 = mgmt_snmp_community4 self.name = name self.password = os.environ.get('PASSWORD') self.platform_name = platform_name self.oncall_team = oncall_team self.opersys = opersys self.role_name = role_name self.serial_num = serial_num self.software_image = software_image self.software_version = software_version self.status = status self.type = type self.updated_at = updated_at self.updated_by = updated_by self.username = os.environ.get('USERNAME') def connect(self): self.net_connect = ConnectHandler(self.mgmt_ip4,self.name,self.username,self.password,self.password,device_type=self.get_device_type()) def scpconnect(self): self.connect() self.scp_connect = SCPConn(self.net_connect) def location(self): datacenter_location = '' if (self.type == 'firewall'): location_list = self.name.split('-') datacenter_location = location_list[3] elif (self.type == 'switch' or self.type == 'router'): location_list = self.name.split('.') datacenter_location = location_list[3] return datacenter_location def get_device_type(self): device_type = { 'ASA5510' : 'cisco_asa', 'WS-C3750G-24TS-1U' : 'cisco_ios', 'f5linux' : 'f5_linux', 'ltm' : 'f5_ltm', 'tmsh' : 'f5_tmsh', 'firefly-perimeter' : 'juniper', 'juniper_junos' : 'juniper_junos', 'vyattavyos' : 'vyatta_vyos', 'vyos' : 'vyos' } return device_type['{}'.format(self.platform_name)] def push_cfgs(self,commands): self.connect() output = self.net_connect.enable() if self.hardware_vendor == 'cisco' and self.opersys == 'ios': output = self.net_connect.send_config_set(commands, exit_config_mode=True) save = self.net_connect.send_command('write memory') # print(output) # print(save) elif self.hardware_vendor == 'cisco' and self.opersys == 'asa': output = self.net_connect.send_config_set(commands, exit_config_mode=True) save = self.net_connect.send_command('write memory') # print(output) # print(save) elif self.hardware_vendor == 'cisco' and self.opersys == 'nxos': output = self.net_connect.send_config_set(commands, exit_config_mode=True) save = self.net_connect.send_command('copy running-config startup-config') # print(output) # print(save) elif self.hardware_vendor == 'juniper': output = self.net_connect.send_config_set(commands, exit_config_mode=False) self.net_connect.commit(and_quit=True) # print(output) elif self.hardware_vendor == 'vyatta': output = self.net_connect.send_config_set(commands, exit_config_mode=False) self.net_connect.commit() # print(output) elif self.hardware_vendor == 'f5': output = self.net_connect.send_config_set(commands,enter_config_mode=False,exit_config_mode=False) save = self.net_connect.send_command('save sys config') # print(output) # print(save) self.net_connect.disconnect() def pull_cfgs(self,command): scp_flag = False method = 'pull_cfgs' if self.hardware_vendor == 'cisco' and self.opersys == 'ios': command = 'show running-config | exclude ntp clock-period' elif self.hardware_vendor == 'cisco' and self.opersys == 'nxos': command = 'show running-config | exclude Time' elif self.hardware_vendor == 'cisco' and self.opersys == 'asa': command = 'show running-config' elif self.hardware_vendor == 'juniper': command = 'show configuration' elif(self.hardware_vendor == 'vyatta'): command = 'show configuration commands' elif self.hardware_vendor == 'f5': command = 'list ltm one-line' self.scpconnect() self.write_to_file(command) scp_flag = True self.scp_connect.scp_get_file('/var/local/ucs/config.ucs', '{}/backup-configs/{}'.format(self.get_home_directory(),self.name)) self.scp_connect.close() self.net_connect.disconnect() if self.hardware_vendor != 'juniper' or self.hardware_vendor != 'f5': self.connect() self.write_to_file(command,scp_flag,method) self.net_connect.disconnect() def exec_cmd(self,command): self.connect() output = self.net_connect.send_command(command) output = output.replace('\n','\n{}: '.format(self.name)) output = re.sub(r'^','{}: '.format(self.name),output) print ('{}'.format(output)) print('') self.net_connect.disconnect() def get_home_directory(self): home_directory = os.getenv('HOME') return home_directory def get_config(self,command): scp_flag = False method = 'get_config' if self.hardware_vendor == 'cisco': command = 'show running-config' elif self.hardware_vendor == 'f5': command = 'list one-line' self.connect() self.write_to_file(command,scp_flag,method) self.net_connect.disconnect() def get_diff(self,commands): scp_flag = False method = 'get_diff' self.connect() self.write_to_file(commands,scp_flag,method) self.net_connect.disconnect() def get_subdir(self,scp_flag): if self.hardware_vendor == 'f5' and scp_flag: sub_dir = 'ucs' else: sub_dir = 'configs' return sub_dir def write_to_file(self,command,scp_flag,method): if method == 'pull_cfgs': extention = '' if self.hardware_vendor == 'juniper' and 'display set' in command: extention = '.set' else: extention = '.conf' self.check_and_mkdir(scp_flag,method) with open('{}/backup-configs/{}/{}{}'.format(self.get_home_directory(),self.get_subdir(scp_flag),self.name,extention), "w") as file: output = self.net_connect.send_command(command) file.write(output) file.close() elif method == 'get_config': self.check_and_mkdir(scp_flag,method) with open('{}/backup-configs/{}'.format(self.get_home_directory(),self.name) + ".conf", "w") as file: output = self.net_connect.send_command(command) file.write(output) file.close() elif method == 'get_diff': self.check_and_mkdir(scp_flag,method) with open('{}/diff-configs/{}'.format(self.get_home_directory(),self.name) + ".conf", "w") as file: output = self.net_connect.send_config_set(command) file.write(output) file.close() def check_and_mkdir(self,scp_flag,method): if method == 'pull_cfgs': os.makedirs('{}/backup-configs/{}/'.format(self.get_home_directory(),self.get_subdir(scp_flag)),exist_ok=True) elif method == 'get_config': os.makedirs('{}/backup-configs/{}'.format(self.get_home_directory(),self.name),exist_ok=True) elif method == 'get_diff': os.makedirs('{}/diff-configs/{}'.format(self.get_home_directory(),self.name),exist_ok=True)
def getSerial(node=None, username=None, password=None): # print(f'what is the value at intf{intf} and the type is {type(intf)}') try: # regx = ['[G,P,E,F}[A-Za-z]{2,3}[0-9]{1,3}.[0-9]{1,2}[\/][0-9]{1,2}', '[G,P,E,F}[A-Za-z]{2,3}[0-9]{1,3}.[0-9]{1,2}','[G,P,E,F}[A-Za-z]{2,3}[0-9]{1,3}'] # regx = '[A-Za-z]{2,3}[0-9]{1,3}.[0-9]{1,2}[\/][0-9]{1,2}' eachLine = [] # int_for_device = [] hostname = str(node) device = { 'device_type': 'cisco_ios', #'autodetect', 'ip': hostname, 'username': username, 'password': password, 'verbose': False } ssh_session = netmiko.ConnectHandler(**device) scp_conn = SCPConn(ssh_session) #add commands you wish run here. # cmdList = [ # 'show ver | in Proc', # 'show int des | in up'+' ', # ] cmdList = ['show ver | in Proc', 'show int status | in connected'] for cmd in cmdList: print(hostname + ': ' + cmd) output = ssh_session.send_command(cmd) # if output == '': # cmdList = [ # 'show ver | in Proc', # 'show int status | in connected' # ] # for cmd in cmdList: # print(hostname + ': ' + cmd) # outputToSend = ssh_session.send_command(cmd) # eachLine = whenConnected(outputToSend) # else: eachLine = whenConnected(output) for intf in eachLine: if intf == '' or intf == 'Processor': break else: intfCmd = [ 'show int ' + intf + ' | in rate|errors|Desc', ] for cmd in intfCmd: # print(hostname + ': ' + cmd) print(cmd) output = ssh_session.send_command(cmd) for linedesc in output.splitlines(): print(linedesc) print('') #close the connections scp_conn.close() ssh_session.disconnect() # print(line) except IOError as eWriteFile: print(f'here is the exception : {eWriteFile}') scp_conn.close() ssh_session.disconnect()