简体   繁体   中英

Pexpect - silence ssh connection output

I'm using a simple pexpect script to ssh to a remote machine and grab a value returned by a command. Is there any way, pexpect or sshwise I can use to ignore the unix greeting? That is, from

    child = pexpect.spawn('/usr/bin/ssh %s@%s' % (rem_user, host))
    child.expect('[pP]assword: ', timeout=5)
    child.sendline(spass)
    child.expect([pexpect.TIMEOUT, prompt])
    child.before = '0'
    child.sendline ('%s' % cmd2exec)
    child.expect([pexpect.EOF, prompt])

    # Collected data processing
    result = child.before
    # logon to the machine returns a lot of garbage, the returned executed command is at the 57th position
    print result.split('\r\n') [57]
    result = result.split('\r\n') [57]

How can I simply get the returned value, ignoring, the "Last successful login" and "(c)Copyright" stuff and without having to concern with the value correct position?

Thanks !

If you have access to the server to which you are logging in, you can try creating a file named .hushlogin in the home directory. The presence of this file silences the standard MOTD greeting and similar stuff.

Alternatively, try ssh -T , which will disable terminal allocation entirely; you won't get a shell prompt, but you may still issue commands and read the response.

There is also a similar thread on ServerFault which may be of some use to you.

If the command isn't interactive, you can just run ssh HOST COMMAND to run the command without all the login excitement happening at all. If the command is interactive, you can frequently use the ssh -t option ( ssh -t HOST COMMAND ) to force pseudo-tty allocation and trick the remote process to think that it's running attached to a TTY.

Hey there you kann kill all that noise by using the sys module and a small class:

class StreamToLogger(object):
   """
   Fake file-like stream object that redirects writes to a logger instance.
   """
   def __init__(self, logger, log_level=logging.INFO):
      self.logger = logger
      self.log_level = log_level
      self.linebuf = ''

   def write(self, buf):
       for line in buf.rstrip().splitlines():
           self.logger.log(self.log_level, line.rstrip())


#Mak
stdout_logger = logging.getLogger('STDOUT')
sl = StreamToLogger(stdout_logger, logging.INFO)
sys.stdout = sl



stderr_logger = logging.getLogger('STDERR')
sl = StreamToLogger(stderr_logger, logging.ERROR)
sys.stderr = sl

Can't remember where i found that snippet but it works for me :)

I have used paramiko to automate ssh connection and I have found it useful. It can deal with greetings and silent execution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM