使用pxssh操作远程服务器时如何去除输出中含unset的提示行
pxssh输出包含unset行的解决方法
问题原因
你看到的含unset的输出是pxssh为了统一匹配远端提示符,默认自动在远程服务器执行的提示符重置操作的输出,你当前的代码在发送命令后未等待提示符匹配就直接读取缓冲区内容,因此将这部分内部操作的输出也一并打印了。
解决方法
方案1:调整send_command逻辑(最推荐)
pxssh规范用法是发送命令后调用prompt()方法等待命令执行完成、匹配到预设提示符后再读取输出,此时before属性仅包含目标命令的执行结果,不会包含内部提示符设置的相关内容:
def send_command(self, command): try: self.connection.sendline(command) # 等待匹配提示符,可传入timeout参数修改默认超时时间(单位:秒) self.connection.prompt() # 解码字节内容并去除首尾空白 print(self.connection.before.decode('utf-8').strip()) except pxssh.ExceptionPxssh: print("Failed to execute command.")
方案2:禁用自动提示符重置(从源头去掉unset操作)
如果你不需要pxssh自动调整远端提示符,可以在初始化时设置auto_prompt_reset=False,此时pxssh不会执行unset PROMPT_COMMAND和修改PS1的操作,不过需要你手动指定匹配的远端提示符规则:
def login(self): try: # 禁用自动提示符重置 self.connection = pxssh.pxssh(auto_prompt_reset=False) # 自定义匹配远端的提示符规则,示例匹配以#或$结尾的提示符 self.connection.PROMPT = r'[\$#] ' self.password = getpass.getpass('Password: ') self.connection.login(self.host, self.username, self.password) except pxssh.ExceptionPxssh: raise Exception("Failed to login.")
方案3:输出内容过滤(兜底方案)
如果仍有残留的无关行,可以直接对输出内容做过滤,剔除所有包含unset的行:
def send_command(self, command): try: self.connection.sendline(command) self.connection.prompt() output = self.connection.before.decode('utf-8') # 过滤含unset的行 filtered_output = '\n'.join([line for line in output.splitlines() if 'unset' not in line]) print(filtered_output) except pxssh.ExceptionPxssh: print("Failed to execute command.")
内容的提问来源于stack exchange,提问作者Albert
相关产品推荐
相关产品推荐

