首页 > 其他 > 详细

记一次ssh.exec_command(cmd)执行后读取结果为空

时间:2019-09-18 20:32:03      阅读:385      评论:0      收藏:0      [点我收藏+]
# 连接跳板机,执行插标签
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对象),再次读取其实是继续读文件,所以是空。

 

记一次ssh.exec_command(cmd)执行后读取结果为空

原文:https://www.cnblogs.com/kusy/p/11545102.html

(1)
(1)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!