Beispiel #1
0
def checkConnectionToResource():
    successfullyConnected=False
    global remoteAccessNode
    global remoteAccessMethod
    global remoteCopyMethod
    global sshUserName
    global sshPassword
    global sshPassword4thisSession
    global sshPrivateKeyFile
    global sshPrivateKeyPassword
    passphraseEntranceCount=0
    authorizeKeyCount=0
    while True:
        str_io=cStringIO.StringIO()
        try:
            sys.stdout = sys.stderr = str_io
            akrr.sshAccess(remoteAccessNode, ssh=remoteAccessMethod, username=sshUserName, password=sshPassword,
                    PrivateKeyFile=sshPrivateKeyFile, PrivateKeyPassword=sshPrivateKeyPassword, logfile=str_io,
                    command='ls')
            
            sys.stdout=sys.__stdout__
            sys.stderr=sys.__stderr__
            
            successfullyConnected=True
            break
        except Exception,e:
            sys.stdout=sys.__stdout__
            sys.stderr=sys.__stderr__
            if args.verbose:
                logging.info("Had attempted to access resource without password and failed, below is resource response")
                print "="*80
                print str_io.getvalue()
                print traceback.format_exc()
                print "="*80
            #check if it asking for passphrase
            m=re.search(r"Enter passphrase for key '(.*)':",str_io.getvalue())
            if m:
                if passphraseEntranceCount>=3:
                    sshPrivateKeyPassword=None
                    sshPrivateKeyFile=None
                    break
                if passphraseEntranceCount>0:
                    logging.error("Incorrect passphrase try again")
                sshPrivateKeyFile=m.group(1)
                logging.input("Enter passphrase for key '%s':"%sshPrivateKeyFile)
                sshPrivateKeyPassword=getpass.getpass("")
                passphraseEntranceCount+=1
                continue
            m2=re.search(r"[pP]assword:",str_io.getvalue())
            if m==None and sshPrivateKeyFile!=None and m2:
                logging.warning("Can not login to head node. Probably the public key of private key was not authorized on head node")
                print "Will try to add public key to list of authorized keys on head node"
                while True:
                    try:
                        authorizeKeyCount+=1
                        logging.input("Enter password for %s@%s (will be used only during this session):"%(sshUserName,remoteAccessNode))
                        sshPassword4thisSession=getpass.getpass("")
                        print
                        str_io=cStringIO.StringIO()
                        sys.stdout = sys.stderr = str_io
                        akrr.sshAccess(remoteAccessNode, ssh='ssh-copy-id', username=sshUserName, password=sshPassword4thisSession,
                            PrivateKeyFile=sshPrivateKeyFile, PrivateKeyPassword=None, logfile=str_io,
                            command='')
                    
                        sys.stdout=sys.__stdout__
                        sys.stderr=sys.__stderr__
                        print str_io.getvalue()
                        #successfullyConnected=True
                        logging.info("Have added public key to list of authorized keys on head node, will attempt to connect again.")
                        print
                        break
                    except Exception,e:
                        sys.stdout=sys.__stdout__
                        sys.stderr=sys.__stderr__
                        if args.verbose:
                            logging.info("Had attempted to add public key to list of authorized keys on head node and failed, below is resource response")
                            print "="*80
                            print str_io.getvalue()
                            print traceback.format_exc()
                            print "="*80
                        logging.info("Incorrect password try again.")
                        if authorizeKeyCount>=3:
                            break
                if authorizeKeyCount<3:
                     continue       
            break
Beispiel #2
0
def getRemoteAccessMethod():
    global remoteAccessNode
    global remoteAccessMethod
    global remoteCopyMethod
    global sshUserName
    global sshPassword
    global sshPassword4thisSession
    global sshPrivateKeyFile
    global sshPrivateKeyPassword
    global rsh
    #set remoteAccessNode
    while True:
        logging.input("Enter Resource head node (access node) full name (e.g. headnode.somewhere.org):")
        remoteAccessNode=raw_input("[%s] "%resourceName)
        if remoteAccessNode.strip()=="":
            remoteAccessNode=resourceName
        
        response = os.system("ping -c 1 -w2 " + remoteAccessNode + " > /dev/null 2>&1")
        
        if response==0:
            break
        else:
            logging.error("Incorrect head node name (can not ping %s), try again"%remoteAccessNode)
    #set sshUserName
    curentuser=getpass.getuser()
    askForUserName=True
    successfullyConnected=False
    while True:
        if askForUserName:
            logging.input("Enter username for resource access:")
            sshUserName=raw_input("[%s] "%curentuser)
            if sshUserName.strip()=="":
                sshUserName=curentuser
            curentuser=sshUserName
        
        #check passwordless access
        if sshPassword==None:
            logging.info("Checking for password-less access")
        else:
            logging.info("Checking for resource access")
        successfullyConnected=checkConnectionToResource()
        if successfullyConnected:
            if sshPassword==None:
                logging.info("Can access resource without password")
            else:
                logging.info("Can access resource")
        
        if successfullyConnected==False:
            logging.info("Can not access resource without password")
            actionList=[]
            actionList.append(["TryAgain","The private and public keys was generated manually, right now. Try again."])
            #check private keys
            userHomeDir = os.path.expanduser("~")
            privateKeys = [ os.path.join(userHomeDir,'.ssh',f[:-4]) for f in os.listdir(os.path.join(userHomeDir,'.ssh')) if os.path.isfile(os.path.join(userHomeDir,'.ssh',f)) \
                       and f[-4:]=='.pub' and os.path.isfile(os.path.join(userHomeDir,'.ssh',f[:-4]))]
            if len(privateKeys)>0:
                actionList.append(["UseExistingPrivateKey","Use existing private and public key."])
            
            actionList.append(["GenNewKey","Generate new private and public key."])
            actionList.append(["UsePassword","Use password directly."])
            
            print
            print "Select authentication method:"
            for i in range(len(actionList)):
                print "%3d  %s"%(i,actionList[i][1])
            while True:
                logging.input("Select option from list above:")
                try:
                    action=raw_input("[2] ")
                    if action.strip()=="":action=2
                    else: action=int(action)
                    
                    if action<0 or action>=len(actionList):
                        raise
                    break
                except Exception,e:
                    logging.error("Incorrect entry, try again.")
            
            #do the action
            print
            if actionList[action][0]=="TryAgain":
                continue
            if actionList[action][0]=="UsePassword":
                logging.input("Enter password for %s@%s:"%(sshUserName,remoteAccessNode))
                sshPassword=getpass.getpass("")
                askForUserName=not askForUserName
                continue
            if actionList[action][0]=="UseExistingPrivateKey":
                print "Available private keys:"
                for i in range(len(privateKeys)):
                    print "%3d  %s"%(i,privateKeys[i])
                while True:
                    logging.input("Select key number from list above:")
                    try:
                        iKey=raw_input("")
                        iKey=int(iKey)
                        
                        if iKey<0 or iKey>=len(privateKeys):
                            raise
                        break
                    except Exception,e:
                        logging.error("Incorrect entry, try again.")
                sshPrivateKeyFile=privateKeys[iKey]
                askForUserName=not askForUserName
                continue
            if actionList[action][0]=="GenNewKey":
                count=0
                while True:
                    logging.input("Enter password for %s@%s (will be used only during this session):"%(sshUserName,remoteAccessNode))
                    sshPassword4thisSession=getpass.getpass("")
                    sshPassword=sshPassword4thisSession
                    
                    if checkConnectionToResource():
                        break
                    count+=1
                    if count>=3:
                        break
                sshPassword=None
                #generate keys
                logging.input("Enter private key name:")
                sshPrivateKeyFile=raw_input("[id_rsa_%s]"%resourceName)
                if sshPrivateKeyFile.strip()=="":
                    sshPrivateKeyFile="id_rsa_%s"%resourceName
                sshPrivateKeyFile=os.path.join(userHomeDir,'.ssh',sshPrivateKeyFile)
                logging.input("Enter passphrase for new key (leave empty for passwordless access):")
                sshPrivateKeyPassword=getpass.getpass("")
                os.system("ssh-keygen -t rsa -N \"%s\" -f %s"%(sshPrivateKeyPassword,sshPrivateKeyFile))
                if sshPrivateKeyPassword.strip()=="":
                    sshPrivateKeyPassword=None
                #copy keys
                akrr.sshAccess(remoteAccessNode, ssh='ssh-copy-id', username=sshUserName, password=sshPassword4thisSession,
                            PrivateKeyFile=sshPrivateKeyFile, PrivateKeyPassword=None, logfile=sys.stdout,
                            command='')
                askForUserName=not askForUserName
                continue
Beispiel #3
0
                            command='')
                askForUserName=not askForUserName
                continue
        
        if successfullyConnected:
            break
        else:
            logging.error("Incorrect resource access credential")
    if successfullyConnected:
        print
        logging.info("Connecting to "+resourceName)
        
        str_io=cStringIO.StringIO()
        sys.stdout = sys.stderr = str_io
        rsh=akrr.sshAccess(remoteAccessNode, ssh=remoteAccessMethod, username=sshUserName, password=sshPassword,
                    PrivateKeyFile=sshPrivateKeyFile, PrivateKeyPassword=sshPrivateKeyPassword, logfile=sys.stdout,
                    command=None)
        sys.stdout=sys.__stdout__
        sys.stderr=sys.__stderr__
        
        logging.info("              Done")
    print
    return successfullyConnected
def getSytemCharacteristics():
    global ppn
    while True:   
        try:                 
            logging.input("Enter processors (cores) per node count:")
            ppn=int(raw_input(""))
            break
        except Exception,e: