def _send_cmd(self, cmd, msg, status_check=True): """Send command to switch. Args: cmd (string): Switch command. msg (string): Description for log file. status_check (boolean): Whether to check for SSH error. Returns: (string): Command output from switch. """ ssh = SSH(self.log) self.log.debug(cmd + ' on ' + self.ipv4) status, stdout_, _ = ssh.exec_cmd(self.ipv4, self.userid, self.password, self.enable_remote % cmd) if status: if status_check: self.log.error('Failed: ' + msg + ' on ' + self.ipv4 + ' - Error: ' + stdout_.replace('\n', ' ').replace('\r', '')) sys.exit(1) else: self.log.info(msg + ' on ' + self.ipv4 + ' - Error: ' + stdout_.replace('\n', ' ').replace('\r', '')) else: self.log.info(msg + ' on ' + self.ipv4) return stdout_
def connectSandbox(self, ip, port=22, username='******', password='******'): self.ip = ip self.port = port ssh = SSH(ip, port, username, password) ssh.connect() self.ssh = ssh self._username = username self._password = password self.sample = None self.sampleName = None self.straceFile = None self.pcapFile = None return
def main(): logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler()) name = os.environ['NAME'] key_name = f'{name}-{uuid4()}' launch_template_names = os.environ['LAUNCH_TEMPLATE_NAMES'].split(',') subnet_id = os.environ['SUBNET_ID'] command = ' '.join(sys.argv[1:]) with ExitStack() as stack: private_key = stack.enter_context(TempKeyPair(key_name)) instance = stack.enter_context( TempInstance( name, launch_template_names, key_name, subnet_id, )) host = instance.private_ip_address connection = stack.enter_context(SSH(host, 'ec2-user', private_key)) escaped_command = command.replace("'", "\\'") logger.info(f'Running command "{escaped_command}" on {host}...') connection.run(f'exec $SHELL -l -c \'{escaped_command}\'')
def connect(): """This command conects to the Nvie compute instance""" c = Config.load_config() u = UnisonDaemon(c.domain, c.host) click.echo( "Syncing current directory to {0} directory {1}" .format(u.host, u.server_folder) ) pid = u.start() click.echo( "Connection to remote machine...." ) s = SSH(c.host, c.container_id) s.connect() input("Press any key to stop sync.") pid.kill()
def send_cmd(self, cmd): if self.mode == 'passive': f = open(self.outfile, 'a+') f.write(cmd + '\n') f.close() return host_ip = gethostbyname(self.host) lockfile = os.path.join(SWITCH_LOCK_PATH, host_ip + '.lock') if not os.path.isfile(lockfile): os.mknod(lockfile) os.chmod(lockfile, stat.S_IRWXO | stat.S_IRWXG | stat.S_IRWXU) lock = FileLock(lockfile) cnt = 0 while cnt < 5 and not lock.is_locked: if cnt > 0: self.log.info('Waiting to acquire lock for switch {}'. format(self.host)) cnt += 1 try: lock.acquire(timeout=5, poll_intervall=0.05) # 5 sec, 50 ms sleep(0.01) # give switch a chance to close out comms except Timeout: pass if lock.is_locked: if self.ENABLE_REMOTE_CONFIG: cmd = self.ENABLE_REMOTE_CONFIG.format(cmd) self.log.debug(cmd) ssh = SSH() __, data, _ = ssh.exec_cmd( self.host, self.userid, self.password, cmd, ssh_log=True, look_for_keys=False) lock.release() # sleep 60 ms to give other processes a chance. sleep(0.06 + random() / 100) # lock acquire polls at 50 ms if lock.is_locked: self.log.error('Lock is locked. Should be unlocked') return data.decode("utf-8") else: self.log.error('Unable to acquire lock for switch {}'.format(self.host)) raise SwitchException('Unable to acquire lock for switch {}'. format(self.host))
def send_cmd(self, cmd): if self.mode == 'passive': f = open(self.outfile, 'a+') f.write(cmd + '\n') f.close() return if self.ENABLE_REMOTE_CONFIG: cmd = self.ENABLE_REMOTE_CONFIG.format(cmd) self.log.debug(cmd) ssh = SSH() __, data, _ = ssh.exec_cmd(self.host, self.userid, self.password, cmd, ssh_log=True, look_for_keys=False) return data
def _send_cmd(self, cmd, msg, status_check=True): ssh = SSH(self.log) self.log.debug('Switch cmd: ' + repr(cmd)) status, stdout_, _ = ssh.exec_cmd(self.ipv4, self.userid, self.password, self.enable_remote % cmd) if status: if status_check: self.log.error('Failed: ' + msg + ' on ' + self.ipv4 + ' - Error: ' + stdout_.replace('\n', ' ').replace('\r', '')) sys.exit(1) else: if msg: self.log.info(msg + ' on ' + self.ipv4) else: if msg: self.log.info(msg + ' on ' + self.ipv4) return stdout_
class RAR: def __init__(self, hostname, username, password): self._ssh = SSH(hostname, username, password) def exit(self): self._ssh.send_expect_prompt('exit') def power_cycle(self, outlet_id): self._ssh.send_expect_prompt('power outlets ' + str(outlet_id) + ' cycle /y') def run_cmd_step(self, file_json_step): Util.run_step_list(self._ssh, file_json_step)
def wait_for_node_to_boot_up(node_ip, username, password, cmd=None): probe_max_count = 10 try_count = 1 interval = 60 while try_count <= probe_max_count: try: ssh = SSH(node_ip, username, password) if not ssh: Util._logger.info("probe times: " + str(try_count)) try_count = try_count + 1 time.sleep(interval) else: if cmd: ssh.send_expect_prompt(cmd) return ssh except: Util._logger.info("exception is raised in ssh") try_count = try_count + 1 time.sleep(interval) raise Exception("Failed to ssh to " + node_ip + " for " + probe_max_count + " times")
def send_cmd(self, cmd): if self.mode == 'passive': f = open(self.outfile, 'a+') f.write(cmd + '\n') f.close() return host_ip = gethostbyname(self.host) lockfile = os.path.join('/var/lock', host_ip + '.lock') if not os.path.isfile(lockfile): os.mknod(lockfile) os.chmod(lockfile, stat.S_IRWXO | stat.S_IRWXG | stat.S_IRWXU) lock = FileLock(lockfile) cnt = 0 while cnt < 5 and not lock.is_locked: if cnt > 0: self.log.info('Waiting to acquire lock for switch {}'.format( self.host)) cnt += 1 try: lock.acquire(timeout=5) # 5 sec except Timeout: pass if lock.is_locked: if self.ENABLE_REMOTE_CONFIG: cmd = self.ENABLE_REMOTE_CONFIG.format(cmd) self.log.debug(cmd) ssh = SSH() __, data, _ = ssh.exec_cmd(self.host, self.userid, self.password, cmd, ssh_log=True, look_for_keys=False) lock.release() return data else: self.log.error('Unable to acquire lock for switch {}'.format( self.host)) raise SwitchException( 'Unable to acquire lock for switch {}'.format(self.host))
def __init__(self, hostname, username, password): self._ssh = SSH(hostname, username, password)
def main(log, inv_file): inv = Inventory(log, inv_file) print() mgmt_network_ext_cidr = None key_addr = None try: mgmt_network_port = inv.get_port_mgmt_network() userid = inv.get_userid_mgmt_switch() password = inv.get_password_mgmt_switch() mgmt_network_gen = inv.get_ipaddr_mgmt_network() mgmt_network_ext = inv.get_mgmt_switch_external_dev_ip() mgmt_network_ext_prefix = inv.get_mgmt_switch_external_prefix() mgmt_network_ext = mgmt_network_ext + '/' + mgmt_network_ext_prefix mgmt_network_ext = netaddr.IPNetwork(mgmt_network_ext) mgmt_network_ext_cidr = str(mgmt_network_ext.cidr) except KeyError: print('Switch access information not present in: {}'.format(inv_file)) print('Cluster Genesis may be in "passive" mode') else: output = subprocess.check_output(['bash', '-c', 'ip route']) if mgmt_network_ext_cidr in output: key_addr = 'addr_ext' elif mgmt_network_gen in output: key_addr = 'addr_gen' else: print('No route found using config file addresses') if key_addr: print('==============================') print('Defined switches: ') index = 1 switches_m = {} for rack, ipv4 in inv.yield_mgmt_rack_ipv4(): switches_m[index] = {'rack': rack, 'addr_gen': ipv4} index += 1 index = 1 for ipv4 in inv.yield_mgmt_switch_external_switch_ip(): switches_m[index]['addr_ext'] = ipv4 print(' ' + str(index) + ') rack: ' + switches_m[index]['rack'] + ', external address: ' + switches_m[index]['addr_ext'] + ', Genesis address: ' + switches_m[index]['addr_gen']) index += 1 if not (len(switches_m) == 1): sw = get_int_input("\n\nSelect a switch: ", 1, len(switches_m)) else: sw = 1 addr = switches_m[sw][key_addr] print() else: # output = subprocess.check_output(['bash', '-c', 'ip route']) addr = '192.168.32.20/24' userid = 'admin' password = '******' while 1: addr = rlinput("Enter an address for the management switch: ", addr) mgmt_network_ext = netaddr.IPNetwork(addr) mgmt_network_ext_cidr = str(mgmt_network_ext.cidr) userid = rlinput("Enter a userid for the management switch: ", userid) password = rlinput( "Enter a password for the management switch (last char = '.' to terminate): ", password) if password[-1:] == '.': sys.exit(0) output = subprocess.check_output(['bash', '-c', 'ip route']) if mgmt_network_ext_cidr in output: addr = addr[:addr.find('/')] break # the G8052 misbehaves & closes it's SSH connection # after every paramiko 'exec_command', so using SSH # with commands strung together ssh = SSH(log) cmd = 'show interface ip;show vlan;show interface port %s;' \ % (str(mgmt_network_port)) try: _, switch_info, _ = ssh.exec_cmd(addr, userid, password, cmd, ssh_log=ssh_log, look_for_keys=False) except SSH_Exception as exc: print('Failed to SSH to switch at {} using userid {} and password {}'. format(addr, userid, password)) print(exc) sys.exit(1) print_lines(switch_info, ['Interface information:', 'IP4']) print('\n\nVLAN information: ') print_lines(switch_info, ['- ------ -', ' VLAN ']) print() print('Deployer port: ') print_lines(switch_info, ['Current port', 'VLANs']) print()
def reconnectSandbox(self): ssh = SSH(self.ip, self.port, self._username, self._password) ssh.connect() self.ssh = ssh
''' Created on Aug 8, 2013 @author: huhe ''' import sys, pexpect from main.define import Define from lib.ssh import SSH if __name__ == '__main__': myssh = SSH.login('10.193.212.20', 'root', 'nbv12345') myssh.sendline('ls -l') #print myssh._ssh.readlines() myssh.expect(Define.PATTERN_PROMPT) print "\n\n--------> before: " + myssh.before myssh.sendline('pwd') #print myssh._ssh.readlines() myssh.expect('/root') #myssh.expect(pexpect.EOF) print "\n\n--------> before: " + myssh.before #print "\n\buffer: " + myssh._ssh.buffer #print "\n\nafter: " + myssh._ssh.after myssh.send('exit')
''' Created on Aug 8, 2013 @author: huhe ''' import sys, pexpect from main.define import Define from lib.ssh import SSH if __name__ == '__main__': myssh = SSH('10.193.212.20', 'root', 'nbv12345') myssh.send('ls -l') #print myssh._ssh.readlines() myssh.expect(Define.PATTERN_PROMPT) print "\n\n--------> before: " + myssh._session.before myssh.send('pwd') #print myssh._ssh.readlines() myssh.expect('Define.PATTERN_PROMPT') #myssh.expect(pexpect.EOF) print "\n\n--------> before: " + myssh._session.before #print "\n\buffer: " + myssh._ssh.buffer #print "\n\nafter: " + myssh._ssh.after myssh.send('exit')