記一次ssh.exec_command(cmd)執行后讀取結果為空


# 連接跳板機,執行插標簽
def con_tmp_machine(mobile_phoneno, myguid):
    keyfile = os.path.expanduser('/Users/kusy/.ssh/id_rsa')
    password = keyring.get_password('SSH', keyfile)
    key = paramiko.RSAKey.from_private_key_file(keyfile, '')

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname='88.88.888.88', port=10022, username='kusy', password="kusy@cys", pkey=key)
    mobile_phoneno = mobile_phoneno
    mobile_phone_tail = mobile_phoneno[-1]
    user_guid = myguid
    sex = "0" if int(mobile_phone_tail) % 2 == 0 else "1"
    add_tag_raw = r'''
        curl -XPOST -H 'Content-Type:application/json' 'xxx.cn:9200/xx_label/job' -d '{
      "user_guid": "$user_guid",
      "mobile_phone_tail": "$mobile_phone_tail",
      "mobile_phone": "$mobile_phoneno",
      "sex":"$sex"
    }'
        '''
    add_tag = add_tag_raw.replace('$mobile_phoneno', mobile_phoneno)\
        .replace('$mobile_phone_tail', mobile_phone_tail)\
        .replace('$user_guid', user_guid)\
        .replace('$sex', sex)

    search_tag_raw = '''curl -XPOST -H "Content-Type:application/json" "xxx.cn:9200/xx_label/job/_search" -d '{"query":{"query_string":{"query":"$mobile_phoneno"}}}'
    '''
    search_tag = search_tag_raw.replace('$mobile_phoneno', mobile_phoneno)

    # 查詢標簽、加標簽流程控制
    result = '' err_flag = False if user_guid == '':
        cmd = ssh.exec_command(search_tag)
    else:
        cmd = ssh.exec_command(add_tag)
        # Alias [xx_label] has more than one indices
        stdin, stdout, stderr = cmd
        result = stdout.read().decode()
        # print('result', result)
        if result.__contains__('Alias [xx_label] has more than one indices'):
            xx_label = re.compile('(xx-\d{8})').findall(result)
            new_xx_label = sorted(xx_label)[-1]
            print('**new_xx_label**', new_xx_label)
            cmd = ssh.exec_command(add_tag.replace('xx_label', new_xx_label))
        else:  err_flag = True print('add normaly..')
            pass
    if result != '' and err_flag: return result else:
        stdin, stdout, stderr = cmd
        return stdout.read().decode()

print("\nssh execute over") # 關閉連接 ssh.close()

綠色背景的代碼是修改后的邏輯,原先出問題的代碼就是去掉這部分的。數據走的是黃色else的邏輯,每次走完return的結果都是'',調試的時候打印的result內容也正常,百思不得其解,debug的時候發現cmd對象也正常,但是內容變為空了。想着難道是因為cmd的stdout已經被讀取一次(粉色背景的cmd對象),再次讀取其實是繼續讀文件,所以是空。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM