记一次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对象),再次读取其实是继续读文件,所以是空。
金瓦金銮殿,皇上看不见;
一朝出了午门口,一个鼻子两只手。
金瓦金銮殿,皇上不坐殿;
一朝出了京门口,百姓的事儿牵着走牵着走。