Python/paramiko

From Omnia
Jump to navigation Jump to search

paramiko

paramiko: ssh2 protocol for python - http://www.lag.net/paramiko/

paramiko github: https://github.com/paramiko/paramiko

Installation

pip install paramiko

Github:

git clone https://github.com/paramiko/paramiko
cd paramiko
git checkout v1.12.2
python setup.py install

Old archive:

mkdir -p ~/.src ; cd ~/.src
wget http://www.lag.net/paramiko/download/paramiko-1.7.7.1.zip
unzip paramiko-1.7.7.1.zip
cd paramiko-1.7.7.1
python setup.py install

SFTP Example

[Python] paramiko examples - https://gist.github.com/mlafeldt/841944

scp_demo.py

#!/usr/bin/env python
 
import sys, paramiko
 
if len(sys.argv) < 5:
    print "args missing"
    sys.exit(1)
 
hostname = sys.argv[1]
password = sys.argv[2]
source = sys.argv[3]
dest = sys.argv[4]
 
username = "root"
port = 22
 
try:
    t = paramiko.Transport((hostname, port))
    t.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(t)
    sftp.get(source, dest)
 
finally:
    t.close()

SSH Command Example

ssh_demo.py:

#!/usr/bin/env python
 
import sys, paramiko
 
if len(sys.argv) < 4:
    print "args missing"
    sys.exit(1)
 
hostname = sys.argv[1]
password = sys.argv[2]
command = sys.argv[3]
 
username = "admin"
port = 22
 
try:
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy)
    client.connect(hostname, port=port, username=username, password=password)
 
    stdin, stdout, stderr = client.exec_command(command)
    stdin.close()
    print stdout.read()
    print stderr.read()
 
finally:
    client.close()

--- To not see the warning:

SSH Key auto add:

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

keywords