0

I am willing to deploy on my server an SSH daemon which I can know what commands was executed. But I don't know how to get the user's commands. I achieve a SSH server based on twisted.conch.ssh.session. I can get all stdout in outReceived of SSHSessionProcessProtocol, But it is difficult to extract the user's commands from the stdout accurately, because that rely heavily on the prompt of Linux($PS1).

   import sys  
   import checkers  
   from twisted.python import components, log, logfile  
   from twisted.cred import portal  
   from twisted.internet import reactor  
   from twisted.conch.ssh import factory, keys, session, filetransfer  
   from twisted.conch.unix import UnixSSHRealm, SSHSessionForUnixConchUser,    UnixConchUser  
   import keyvalue  
   if __name__ == "__main__":  
      sshFactory = factory.SSHFactory()  
      sshFactory.portal = portal.Portal(UnixSSHRealm())  
      sshFactory.portal.registerChecker(checkers.UsernamePasswordChecker())  

      sshFactory.publicKeys = {
        'ssh-rsa': keys.Key.fromString(keyvalue.publicKey)}
      sshFactory.privateKeys = {
        'ssh-rsa': keys.Key.fromString(keyvalue.privateKey)}
      components.registerAdapter(
        SSHSessionForUnixConchUser, UnixConchUser, session.ISession)
      log.startLogging(sys.stdout)

      reactor.listenTCP(2222, sshFactory)
      reactor.run()
chzijian
  • 21
  • 5

1 Answers1

0

You are correct; it is very hard to accurately get the user's commands, because it is (in the general case) literally impossible to differentiate between user input that goes to the shell and user input that goes to other programs.

You might want to consider writing your own shell that runs inside Twisted, and log the commands the user types into that. but if you want them to literally run their login shell, you're out of luck.

Glyph
  • 31,152
  • 11
  • 87
  • 129
  • thanks,if i want to extract the commands from the user's stdin in dataReceived of SSHSession,not from stdout. I can get the user's input stream which may contain backspace,delete,home,left-arrow,right-arrow keyStroke and so on,like 'lsss\x1b[D\x08\x08\r' which keyStrok are 'l s s s left-arrow backspace backspace' . But how i can get the last results that is 'ls'. – chzijian Apr 26 '16 at 09:56
  • Twisted has some utilities in `twisted.conch.insults` for doing keyboard input yourself, but that would be if you were writing your own terminal-based UI. If you want to parse that stream of input into a command, you'll need to write your own parser for it. – Glyph Apr 30 '16 at 19:09