Implementing SCP with paramiko

    Regular readers will note that I've been interested in how scp works and paramiko for the last couple of days. There are previous examples of how to do scp with paramiko out there, but the code isn't all on one page, you have to read through the mail thread and work it out from there. I figured I might save someone some time (possibly me!) and note a complete example of scp with paramiko...

      # A simple scp example for Paramiko.
      # Args:
      #   1: hostname
      #   2: username
      #   3: local filename
      #   4: remote filename
      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.auth_password(sys.argv[2], getpass.getpass('Password: '))
      # Start a scp channel
      scp_channel = t.open_session()
      f = file(sys.argv[3], 'rb')
      scp_channel.exec_command('scp -v -t %s\n'
                               % '/'.join(sys.argv[4].split('/')[:-1]))
      scp_channel.send('C%s %d %s\n'
      # Cleanup

    Tags for this post: python paramiko scp
    Related posts: Multiple file support with scp; Calculating a SSH host key with paramiko; paramiko exec_command timeout; Weird paramiko problem; Executing a command with paramiko; Packet capture in python

posted at: 13:28 | path: /python/paramiko | permanent link to this entry