def ssh_login(host, username, password): r = SSH_Client() r.load_system_host_keys() r.set_missing_host_key_policy(AutoAddPolicy()) info("Trying to open a SSH connection to {}".format(host)) try: r.connect(host, username=username, password=password) except SSH_BadHostKeyException as errstr: error("SSH host key for {0} could not be verified: {1}".format(host, errstr)) return False except SSH_AuthenticationException: error("SSH authentication failed for {}".format(host)) return False except SSH_SSHException as errstr: error("Unknown SSH error while connecting to {0}: {1}".format(host, errstr)) return False except OSError as err: error("Can't connect to SSH server {0}: '{1}'".format(host, err)) return False except: error("Unknown error encountered while connecting to SSH server {}".format(host)) return False info("SSH connection to {} opened successfully".format(host)) return r
def run(self): logger.info("Starting SSH client") with SSHClient() as ssh: ssh.set_missing_host_key_policy(AutoAddPolicy()) ssh.connect(hostname=self.c['host'], username=self.c['login'], password=self.c['pass'], look_for_keys=False) logger.debug('SSH client connected') while True: # Pick command to send command = choice(self.commands) if '@f' in command: command = command.replace('@f', choice(self.files)) elif '@d' in command: command = command.replace('@d', choice(self.dirs)) logger.info('Executing command `{}`'.format(command)) out = ssh.exec_command(command) logger.debug('Output: {}'.format(out)) delay = randint(*self.delay_range) logger.debug('Waiting for {} seconds'.format(delay)) sleep(delay)
def _get_machine(host, user, keyfile): try: for i in range(10): logger.debug(f'Connection attempt no: {i}') try: signal.alarm(15) ret = ParamikoMachine(host=host, user=user, keyfile=keyfile, connect_timeout=15, keep_alive=30, missing_host_policy=AutoAddPolicy()) signal.alarm(0) except TimeoutError: pass else: return ret else: raise RuntimeError('Connection could not be established') finally: signal.alarm(0)
def __init__(self, host, port=22, timeout=10): self.host = host self.port = int(port) self.timeout = timeout self.ssh_client = SSHClient() self.ssh_client.set_missing_host_key_policy(AutoAddPolicy())
def turn_off(id): server = SERVERS.get(id) if not server: return server_not_found() exit_status = -1 ssh_settings = server['ssh'] client = SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect(ssh_settings['address'], username=ssh_settings['username'], password=ssh_settings['password']) stdin, stdout, stderr = client.exec_command('shutdown -p now') #print("stdout: " + str(stdout.readlines())) #print("stderr: " + str(stderr.readlines())) exit_status = stdout.channel.recv_exit_status() print("Shutdown, exit status: %s" % exit_status) client.close() return jsonify({"success": exit_status == 0})
def _read_remote_results(self, retry_attempts=3): client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) client.load_system_host_keys() client.connect(self.remote_server, username=self.remote_user, password=self.remote_password) command = "grep {0} /var/mdta/report/CallReport.log".format( self.filename) for i in range(15): print("Attempt {0}".format(i)) stdin, stdout, stderr = client.exec_command(command) result_line = stdout.read() print(result_line) if result_line: break time.sleep(0.25) client.close() try: result_fields = result_line.decode('utf-8').split(",") result = { 'result': result_fields[-4], 'reason': result_fields[-2], 'call_id': result_fields[2] } except IndexError: address_in_use = self._check_call_start_failure() if address_in_use: if retry_attempts >= 1: time.sleep(6) print("Retries left: {0}".format(retry_attempts - 1)) self._invoke_remote_hat() result = self._read_remote_results( retry_attempts=retry_attempts - 1) else: result = { 'result': 'FAIL', 'reason': 'Unable to place call, port in use', 'call_id': '0' } elif not result_line: result = { 'result': 'FAIL', 'reason': 'No results for this test case were found in the logs.', 'call_id': '0' } else: result = { 'result': 'FAIL', 'reason': 'Failed to read results: ' + str(result_line), 'call_id': '0' } except Exception as e: result = { 'result': 'FAIL', 'reason': 'An untrapped error occurred: ' + str(e.args), 'call_id': '0' } return result
def __enter__(self): self.local.depth = getattr(self.local, 'depth', 0) + 1 if self.local.depth < 2: self.wait_state() self.local.client = SSHClient() self.local.client.set_missing_host_key_policy(AutoAddPolicy()) trial = 1 logger = self.get_logger() while 1: try: logger.info('try to connect %s@%s... [attempt #%d]', self.login, self.instance.public_dns_name, trial) self.local.client.connect( self.instance.public_dns_name, username=self.login, pkey=self.app.private_key ) except socket.error as e: if e.errno in (60, 61, 111, 113) and trial <= 20: time.sleep(3) trial += 1 continue logger.exception(e) raise else: break return self.local.client
def try_ssh(virtual_machine: VirtualMachine, retries: int = 10): """ Try to connect to a virtual machine using ssh :param virtual_machine: the virtual machine :param retries: the maximum of retries """ retry = 0 connected = False ssh = SSHClient() ssh.set_missing_host_key_policy(AutoAddPolicy()) ssh.load_system_host_keys() while retry < retries and not connected: try: logger.debug('Trying ssh connection to %s %s out of %s retries', virtual_machine.hostname, retry, retries) ssh.connect(virtual_machine.hostname, port=virtual_machine.ssh_port, username=virtual_machine.ssh_username, password=virtual_machine.ssh_password) connected = True except (BadHostKeyException, AuthenticationException, SSHException, socket.error): time.sleep(10) retry += 1 if not connected: raise Exception( '[{}] Unable to connect to the machine after {} tries'.format( virtual_machine.hostname, retry)) logger.info('Connection established to %s after %d out of %d retries', virtual_machine.name, retry, retries)
def ParamikoMethod(self): trans = Transport((self.ip, 22)) trans.connect(username=self.username, password=self.password) paramiko_client = SSHClient() paramiko_client.set_missing_host_key_policy(AutoAddPolicy()) paramiko_client._transport = trans return paramiko_client
def open_connection(self, hostname, port='22', username=None, password=None, key_filename=None): """Opens a new SCP connection to the given host. The default port used is `22`: | Open Connection | host.tylercrumpton.com | A different port may be optionally given by using the `port` argument: | Open Connection | host.tylercrumpton.com | port=4242 | Authentication may be done using a username and password: | Open Connection | host.tylercrumpton.com | username=tyler | password=iamateapot | Or by using a private keyfile: | Open Connection | host.tylercrumpton.com | username=tyler | key_filename=myprivatekey | """ try: port = int(port) except: raise ValueError('Port must be a valid number.') self.ssh = SSHClient() self.ssh.set_missing_host_key_policy(AutoAddPolicy()) self.ssh.connect(hostname, port=port, username=username, password=password, key_filename=key_filename) self.scp_client = SCPClient(self.ssh.get_transport())
def run_remote_command(args, hostgroup_name, hostgroup, command): """Run the appropriate command on hosts in a given host group based on the action being taken""" client = SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(AutoAddPolicy()) ssh_key = None host_results = {} if args.ssh_key: ssh_key = "%s/.ssh/%s" % (os.environ['HOME'], args.ssh_key) for host in hostgroup: try: client.connect(host.address, allow_agent=True, username=os.getenv('USER')) except Exception, e: print "Error running remote command on (%s:%s) (%s)" % ( host.name, host.address, e) continue print "(%s:%s) => (%s)" % (host.name, host.address, command) chan = client.get_transport().open_session() chan.set_combine_stderr(True) chan.exec_command(command) dump_channel(chan) rv = chan.recv_exit_status() host_results[host.name] = rv chan.close() client.close() _summarize_exit_code(rv)
def create_ssh_client(host, account, password, port=22): client = SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect(host, port=port, username=account, password=password) return client
def __init__(self, host, user='******'): self.host = host self.user = user self.client = SSHClient() self.sftpclient = None self.client.set_missing_host_key_policy(AutoAddPolicy()) self.client.load_system_host_keys()
def Upload(self, files, dsDir): try: self.ssh = SSHClient() self.ssh.set_missing_host_key_policy(AutoAddPolicy()) self.ssh.connect(self.host, port=self.port, username=self.usr, password=self.pwd, pkey=self.pk, key_filename=self.kf, banner_timeout=3.0, auth_timeout=3.0) self.stftp = self.ssh.open_sftp() result = [] for f in files: if os.path.isfile(f): dir, fn = os.path.split(f) result.append((f, self.UploadFile(self.stftp, f, os.path.join(dsDir, fn)))) elif os.path.isdir(f): for root, dirs, fns in os.walk(f): for fn in fns: result.append( (os.path.join(root, fn), self.UploadFile( self.stftp, os.path.join(root, fn), os.path.join(dsDir, root.replace(f, ''), fn)))) self.__close() return True, result except Exception as e: self.__close() return False, traceback.format_exc()
def connect_ssh(dns_name, identity_file): ''' ''' client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect(dns_name, username='******', key_filename=identity_file) return client
def timecheck(h): cmd = "date +%s" s = SSHClient() print "> %s" % (h, ) s.set_missing_host_key_policy(AutoAddPolicy()) s.connect(hostname=h[1], username=h[0]) (_in, _out, _err) = s.exec_command(cmd, bufsize=4096) print "< %s" % (h, ) return (h, _out.read())
def execute_cmd(ip_addr, cmd): client = SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect(ip_addr, username=dtacq_un, password=dtacq_pw) _, aout, aerr = client.exec_command(cmd) return aout.read(), aerr.read()
def __init__(self, host, ip=None, user='******'): self.host = host self.ip = ip self.user = user self.client = SSHClient() self.sftpclient = None self.client.set_missing_host_key_policy(AutoAddPolicy()) self.client.load_system_host_keys() logging.debug("RemoteClient created for host: %s", host)
def __init__(self): self.ssh_client = SSHClient() self.ssh_client.set_missing_host_key_policy(AutoAddPolicy()) self.ssh_client.connect(MAC_HOST_IP, port=MAC_PORT, username=MAC_USERNAME, password=MAC_PASSWORD, timeout=3) self.ssh_dict = {}
def timecheck(h): cmd = "sudo sysctl -w net.core.somaxconn=16000;" s = SSHClient() print "> %s" % (h,) s.set_missing_host_key_policy(AutoAddPolicy()) s.connect(hostname=h[1], username=h[0])#, password='') (_in, _out, _err) = s.exec_command( cmd, bufsize=4096) print "< %s" % (h,) return (h,_out.read())
def connect(self, host, port=0, timeout=-999): if self.ssh is None: self.ssh = SSHClient() self.ssh.set_missing_host_key_policy(AutoAddPolicy()) self.ssh.connect(hostname=host, port=port, username=GLEAM_USERNAME, password=GLEAM_PASSWORD) self.ftp = self.ssh.open_sftp() return self.ftp
def is_robot(ip, user, passwd): client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) try: client.connect(ip, SSH_PORT, user, passwd) client.close() return True except: return False
def __ssh_login(self,host,user,passwd): try: ssh_client = SSHClient() ssh_client.set_missing_host_key_policy(AutoAddPolicy()) ssh_client.connect(hostname=str(host),port=self.port,username=user,password=passwd) print("check success:%s %s %s" % (host,user,passwd)) except: pass self.lock.acquire() self.wait_thread = self.wait_thread - 1 self.lock.release()
def connect(self): logging.getLogger('paramiko').setLevel(logging.ERROR) self._ssh = SSHClient() self._ssh.set_missing_host_key_policy(AutoAddPolicy()) self._ssh.load_system_host_keys() timeout = self._kwargs.get('timeout', None) self._ssh.connect(self.host, self._port, self.user, allow_agent=True, timeout=timeout)
def __init__(self, address, user=None, passwd=None): self.client = SSHClient() self.client.set_missing_host_key_policy(AutoAddPolicy()) self.client.load_system_host_keys() if user is None: self.client.connect(address) else: if passwd is not None: self.client.connect(address, username=user, password=passwd) else: self.client.connect(address, username=user)
def sshClient(self): if self._sshClient is None: self.loadSshConfig() self._sshClient = SSHClient() self._sshClient.set_missing_host_key_policy(AutoAddPolicy()) self._sshClient.connect(self.hostname, self.sshPort, self.sshUser, key_filename=self.sshKey, timeout=10) return self._sshClient
def open(self, host, port=22, username=None, password=None): self.client = SSHClient() self.client.set_missing_host_key_policy(AutoAddPolicy()) self.client.connect(hostname=host, port=port, username=username, password=password, look_for_keys=False) t = self.client.get_transport() self.channel = t.open_session() self.channel.get_pty() self.channel.invoke_shell()
def createClient(host, username=None, pkeyPath=None): """ Creates an SSH client object that can be used to perform SSH-related operations """ client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) pkey = RSAKey.from_private_key_file( os.path.expanduser(pkeyPath)) if pkeyPath else None client.connect(host, username=username, pkey=pkey) return client
def connect(self, hostname, port, username, password): try: logger.info('正在远程连接主机:%s' % hostname) self.ssh_client.set_missing_host_key_policy(AutoAddPolicy()) self.ssh_client.connect(hostname=hostname, port=port, username=username, password=password) return [True, ''] except Exception as e: logger.error('连接出错了%s' % e) return [False, '%s' % e]
def _exec_ssh_cmd(self, cmdline): pkey_buf = StringIO(self.state.pkey) client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect(self.droplet_ip, username='******', pkey=RSAKey.from_private_key(pkey_buf)) stdin, stdout, stderr = client.exec_command(cmdline) for line in stdout: logging.info(line) for line in stderr: logging.info(line)