class - paramiko (ssh)

最後更新: 2019-07-26

 

介紹

 

Home Page: http://www.paramiko.org/

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

 


Install

 

Centos6

yum install python-pip

yum install python-devel

pip install paramiko

Centos7

yum install python-paramiko

 


Basic Usage

 

# Code

#!/usr/bin/env python

import paramiko, base64

c = paramiko.SSHClient()

c.set_missing_host_key_policy(paramiko.AutoAddPolicy())

c.connect('ssh.example.com', username='strongbad', password='thecheat')

stdin, stdout, stderr = c.exec_command('ls')

for line in stdout:
    print '... ' + line.strip('\n')

c.close()

 

ssh.set_missing_host_key_policy

如果不設定成 paramiko.AutoAddPolicy(), 那有機會遇到以下 Error

paramiko.ssh_exception.SSHException: Server '[192.168.88.1]:2222' not found in known_hosts

不想用 AutoAddPolicy() , 可以用 load_system_host_keys(filename=None) 解決

Load host keys from a system (read-only) file.

client.connect

Parameters:    

    hostname (str) – the server to connect to

    port (int) – the server port to connect to

    username (str) – the username to authenticate as (defaults to the current local username)

    password (str) – Used for password authentication; is also used for private key decryption if passphrase is not given.

    passphrase (str) – Used for decrypting private keys.

    pkey (PKey) – an optional private key to use for authentication

    key_filename (str) – the filename, or list of filenames, of optional private key(s) and/or certs to try for authentication

    timeout (float) – an optional timeout (in seconds) for the TCP connect

    allow_agent (bool) – set to False to disable connecting to the SSH agent

    look_for_keys (bool) – set to False to disable searching for discoverable private key files in ~/.ssh/

    compress (bool) – set to True to turn on compression

    sock (socket) – an open socket or socket-like object (such as a Channel) to use for communication to the target host

    banner_timeout (float) – an optional timeout (in seconds) to wait for the SSH banner to be presented.

    auth_timeout (float) – an optional timeout (in seconds) to wait for an authentication response.

    disabled_algorithms (dict) – an optional dict passed directly to Transport and its keyword argument of the same name.
 

client.exec_command

stdin, stdout, stderr = ssh.exec_command("uptime")

A new Channel is opened and the requested command is executed.

The command’s input and output streams are returned as Python file-like objects representing stdin, stdout, and stderr.

 


 

Code

#!/usr/bin/env python

import paramiko
import time

filename = "/root/scripts/test.txt"

def makelog(msg):
    fo = open(filename, 'r+')
    now = time.strftime("%Y-%m-%d %H:%M:%S")
    fo.write("<pre><body><html>")
    fo.write("Last update time: " + now +  ' (update every 2 min.)' + '\n' + '\n')
    fo.writelines(msg)
    fo.write("</pre></body></html>")
    fo.close()

def create_ssh(host, username, password):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        print "creating connection"
        ssh.connect(host, username=username, password=password)

        stdin, stdout, stderr = ssh.exec_command("show sta summary")
        msg1 = stdout.readlines()

        stdin, stdout, stderr = ssh.exec_command("show sta list")
        msg2 = stdout.readlines()

        msg = msg1 + ["\n\n*****************\n\n\n",] + msg2

        makelog(msg)

        print "connected"
    finally:
        print "closing connection"
        ssh.close()
        print "closed"

        
if __name__ == "__main__":
    host = '192.168.88.181'
    username = 'root'
    password = '******'
    create_ssh(host, username, password)

 


DOC

http://docs.paramiko.org/en/1.16/api/client.html

 

 

 

 

Creative Commons license icon Creative Commons license icon