我们从Python开源项目中,提取了以下12个代码示例,用于说明如何使用paramiko.PasswordRequiredException()。
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 ssh_cmd(self,hostname,cmd,pro_name): self.logger.info("??????%s??svn up???...." %hostname) self.logger.info('%s %s' %(pro_name,hostname)) username="root" password="qwe34%^QWE" pkey_w='keyfile/1254' try: pkey=paramiko.RSAKey.from_private_key_file(pkey_w) except paramiko.PasswordRequiredException: pkey=paramiko.RSAKey.from_private_key_file(pkey_w,password) ssh=paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname,port=23111,username=username,pkey=pkey) for cmd_a in cmd: stdin,stdout,stderr=ssh.exec_command(cmd_a) out=stdout.readlines() errout=stderr.readlines() for o in out: self.logger.info(o) for err_o in errout: self.logger.info(err_o) self.logger.info("?????%s??svn up?????" %hostname)
def check_auth_password(self, username, password): logger.info("-=-=- %s -=-=-\nUser: %s\nPassword: %s\n" % (self.client_address[0], username, password)) print " IP: %s\n User: %s\n Pass: %s\n" % (self.client_address[0], username, password) if DENY_ALL == True: return paramiko.AUTH_FAILED f = open("blocked.dat","r") data = str(f.readlines()).find(self.client_address[0]) if data > 1: if ran: new_key() return paramiko.PasswordRequiredException else: f = open("blocked.dat","a") deepscan(self.client_address[0],f) paramiko.OPEN_FAILED_CONNECT_FAILED if (username == "root") and (password in PASSWORDS): return paramiko.AUTH_SUCCESSFUL return paramiko.AUTH_FAILED
def _prompt_for_key_password(key_file, password=None): """ Given a key_file will attempt read it, if password is None and a password is required, will prompt for the password """ try: paramiko.RSAKey.from_private_key_file(key_file, password) except paramiko.PasswordRequiredException: password = getpass.getpass(_("SSH Key password:")) paramiko.RSAKey.from_private_key_file(key_file, password) return password
def sshRCommand(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.send(command) print sshSession.recv(1024) while True: command = sshSession.recv(1024) try: output = subprocess.check_output(command, shell = True) sshSession.send(output) except Exception, e: sshSession.send(str(e)) client.close() return
def manual_auth(self): """ ????,?????????? :return: """ default_auth = 'p' auth = default_auth # auth = input('Auth by (p)assword, (r)sa key, or (d)ss key? [%s] ' % default_auth) if len(auth) == 0: auth = default_auth if auth == 'r': default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa') path = input('RSA key [%s]: ' % default_path) if len(path) == 0: path = default_path try: key = paramiko.RSAKey.from_private_key_file(path) except paramiko.PasswordRequiredException: key = paramiko.RSAKey.from_private_key_file(path, self.password) self.transport.auth_publickey(self.username, key) elif auth == 'd': default_path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa') path = input('DSS key [%s]: ' % default_path) if len(path) == "0": path = default_path try: key = paramiko.DSSKey.from_private_key_file(path) except paramiko.PasswordRequiredException: key = paramiko.DSSKey.from_private_key_file(path, self.password) self.transport.auth_publickey(self.username, key) else: self.transport.auth_password(self.username, self.password)
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 init(hostname, username, keyfile, passwd): global sftp, tc t = paramiko.Transport(hostname) tc = t try: key = paramiko.RSAKey.from_private_key_file(keyfile, passwd) except paramiko.PasswordRequiredException: sys.stderr.write('\n\nparamiko.RSAKey.from_private_key_file REQUIRES PASSWORD.\n') sys.stderr.write('You have two options:\n') sys.stderr.write('* Use the "-K" option to point to a different (non-password-protected)\n') sys.stderr.write(' private key file.\n') sys.stderr.write('* Use the "-P" option to provide the password needed to unlock this private\n') sys.stderr.write(' key.\n') sys.stderr.write('\n') sys.exit(1) try: t.connect(username=username, pkey=key) except paramiko.SSHException: t.close() sys.stderr.write('\n\nparamiko.Transport.connect FAILED.\n') sys.stderr.write('There are several possible reasons why it might fail so quickly:\n\n') sys.stderr.write('* The host to connect to (%s) is not a valid SSH server.\n' % hostname) sys.stderr.write(' (Use the "-H" option to change the host.)\n') sys.stderr.write('* The username to auth as (%s) is invalid.\n' % username) sys.stderr.write(' (Use the "-U" option to change the username.)\n') sys.stderr.write('* The private key given (%s) is not accepted by the server.\n' % keyfile) sys.stderr.write(' (Use the "-K" option to provide a different key file.)\n') sys.stderr.write('\n') sys.exit(1) sftp = paramiko.SFTP.from_transport(t)
def _load_key(key_filename): pkey = None try: pkey = paramiko.RSAKey.from_private_key_file(key_filename, None) except paramiko.PasswordRequiredException: key_pass = prompt_pass('Password for private key:') pkey = paramiko.RSAKey.from_private_key_file(key_filename, key_pass) if pkey is None: raise CLIError('failed to load key: {}'.format(key_filename)) return pkey
def _load_from_key_file(self, filename): try: key = paramiko.RSAKey.from_private_key_file(filename) except paramiko.PasswordRequiredException: password = getpass.getpass('RSA key password for %s: ' % filename) key = paramiko.RSAKey.from_private_key_file(filename, password) return key