英文:
channel.recv didn't return prompt back even after command is completed. 'while True' loop didn't break
问题
channel.recv在命令完成后仍未返回提示符。'while True'循环未中断。
我正在使用paramiko登录一个服务器,用户为'xyz',然后使用paramiko通道执行'su -'。
```python
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(hostname, username='xyz', password=list_pass(hostname, 'xyz'))
command = 'puppet agent -t --no-use_cached_catalog ; echo COMMAND_COMPLETED'
channel = ssh.invoke_shell()
channel.send("su -\n")
time.sleep(2)
channel.send(list_pass(hostname, 'root') + "\n")
time.sleep(2)
channel.send(command + '\n')
time.sleep(5)
while True:
if channel.recv:
time.sleep(1)
print(channel.recv(1024).decode())
if "COMMAND_COMPLETED" in channel.recv(1024).decode():
break
else:
continue
channel.close()
ssh.close()
except paramiko.AuthenticationException:
print("Authentication failed")
except socket.gaierror:
print(f"无法连接到{hostname}。请验证服务器是否存在且处于运行状态。")
此代码陷入了无限循环。命令仍在运行中。
[在这里输入图像描述](https://i.stack.imgur.com/SZUMI.png)
英文:
channel.recv didn't return prompt back even after command is completed. 'while True' loop didn't break.
I am using paramiko to login a server with user 'xyz' and then 'su -' using paramiko channel.
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(hostname, username='xyz', password=list_pass(hostname, 'xyz'))
command = 'puppet agent -t --no-use_cached_catalog ; echo COMMAND_COMPLETED'
channel = ssh.invoke_shell()
channel.send("su -\n")
time.sleep(2)
channel.send(list_pass(hostname, 'root') + "\n")
time.sleep(2)
channel.send(command + '\n')
time.sleep(5)
while True:
if channel.recv:
time.sleep(1)
print(channel.recv(1024).decode())
if "COMMAND_COMPLETED" in channel.recv(1024).decode():
break
else:
continue
channel.close()
ssh.close()
except paramiko.AuthenticationException:
print("Authentication failed")
except socket.gaierror:
print(f"Can't connect to {hostname}. Verify if server exists and it's up.")
This code went to infinite loop. Command still running.
答案1
得分: 0
我尝试了下面的代码,它有效。
channel.send(command + '\n')
time.sleep(5)
# 创建一个新的接收缓冲区
receive_buffer = ""
while not receive_buffer.endswith("# ") or receive_buffer.endswith("$ "):
'''
'root' 用户提示以 '# ' 结尾。
'non-root' 用户提示以 '$ ' 结尾。
'''
receive_buffer += channel.recv(9999).decode()
print(receive_buffer)
channel.close()
ssh.close()
请注意,我保留了代码中的注释以提供更多上下文。
英文:
I tried below code and it worked.
channel.send(command + '\n')
time.sleep(5)
# Create a new receive buffer
receive_buffer = ""
while not receive_buffer.endswith("# ") or receive_buffer.endswith("$ "):
'''
'root' user prompt ends with '# '.
'non-root' user prompt end with '$ '.
'''
receive_buffer += channel.recv(9999).decode()
print(receive_buffer)
channel.close()
ssh.close()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论