Executing a command with paramiko

    I wanted to provide a simple example of how to execute a command with paramiko as well. This is quite similar to the scp example, but is nicer than executing a command in a shell because there isn't any requirement to do parsing to determine when the command has finished executing.

      
      #!/usr/bin/python
      
      
      
      # A simple command example for Paramiko.
      
      # Args:
      
      #   1: hostname
      
      #   2: username
      
      #   3: command to run
      
      
      
      import getpass
      
      import os
      
      import paramiko
      
      import socket
      
      import sys
      
      
      
      # Socket connection to remote host
      
      sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      
      sock.connect((sys.argv[1], 22))
      
      
      
      # Build a SSH transport
      
      t = paramiko.Transport(sock)
      
      t.start_client()
      
      t.auth_password(sys.argv[2], getpass.getpass('Password: '))
      
      
      
      # Start a cmd channel
      
      cmd_channel = t.open_session()
      
      cmd_channel.exec_command(sys.argv[3])
      
      
      
      data = cmd_channel.recv(1024)
      
      while data:
      
        sys.stdout.write(data)
      
        data = cmd_channel.recv(1024)
      
      
      
      # Cleanup
      
      cmd_channel.close()
      
      t.close()
      
      sock.close()
      
      


posted at: 15:11 | path: /python/paramiko | permanent link to this entry

    Add a comment to this post:

    Your name:

    Your email: Email me new comments on this post
      (Your email will not be published on this site, and will only be used to contact you directly with a reply to your comment if needed. Oh, and we'll use it to send you new comments on this post it you selected that checkbox.)


    Your website:

    Comments: