paramikoライブラリの簡単な学習


  • paramikoライブラリの簡単な学習
  • 一、取付
  • 二、ssh接続オブジェクト
  • 三、ssh実行指令
  • 四、sftpオブジェクト
  • 五、sftp関連操作
  • 六、paramikoによるsshのインタラクティブ接続
  • 7、さらに

  • paramikoライブラリの簡単な学習
    paramikoは、英語のように聞こえないライブラリで、多くの英語名のライブラリの中で独立した旗(公式には「Paramiko」is a combination of the Esperanto words for「paranoid」and「friend」と解釈されている).その主な機能はsshプロトコルのパッケージを実現することであり、sshやsftpなどの機能をより高いレベルで簡単に使用することができる.
    一、据付
    pip install paramiko

    二、ssh接続オブジェクト
    1.パスワードで接続
    import paramiko
    #             ,         
    # paramiko.util.log_to_file('/tmp/sshout')
    ssh = paramiko.SSHClient()
    #              know_hosts      。
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect("IP", port, "username", "password")

    2.鍵で接続する
    import paramiko
    ssh = paramiko.SSHClient()
    ssh.connect('10.120.48.109', port, '   ', key_filename='  ')

    三、ssh実行指令
    ホストの接続に成功したら、ssh.exec_を使用できます.command(cmd)の方法で命令を実行します.しかし、デフォルトでは3つのparamiko.channelfileオブジェクトが返され、以下の方法でデータを読み取るか、書き込み確認などを行うことができます.
    stdin, stdout, stderr = ssh.exec_command(cmd)
    #     ,stdout        
    for line in stdout.readlines():
        print(line)
    #      ,            ,                  ,  “    ” 
    stdin.write('Y')
    #             ,        stderr 

    四、sftpオブジェクト
    paramikoのsftpオブジェクトには、さまざまな生成方法があります.sshオブジェクトが既に存在する場合:-sftp=paramiko.SFTPClient.from_transport(ssh.get_transport()) - sftp = ssh.open_sftp()は、sshオブジェクトがなければ、暗号化パイプを直接作成し、転送を開くことができることを推奨します.
    scp = paramiko.Transport(('ip', port))
    scp.connect(username='username', password='password')
    sftp = paramiko.SFTPClient.from_transport(scp)

    五、sftp関連操作
    sftpオブジェクトを作成し、オブジェクトの所有方法を表示すると、sftp.chhown()、sftp.chmod()などの方法がいくつかあり、ssh.exec_を使用することができます.command(cmd)の方法は実現されるが,ここではsshオブジェクトがホスト向けであり,sftpオブジェクトがファイルシステム向けであることが明らかになった.いくつかの一般的な操作:-sftp.get(remotepath,localpath,callback=None)#ダウンロードファイル-sftp.put(localpath,remotepath,callback=None,confirm=True)#アップロードファイル-sftp.stat(path)#ファイルステータスの表示
    sftpオブジェクトを表示する方法の詳細
    六、paramikoを利用してsshのインタラクティブな接続を実現する
    これにより、pyファイルを実行するときに、リモートホストのshellに接続し、一定の操作を行い、終了後にスクリプトを実行し続けることができます.実装手順:1、リモートホスト2の接続、tty 3の作成、いくつかの命令の実行4、終了5、スクリプトの実行継続
    interactive.pyというファイルを作成します.
    import socket
    import sys
    # windows does not have termios...
    try:
        import termios
        import tty
        has_termios = True
    except ImportError:
        has_termios = False
    def interactive_shell(chan):
        if has_termios:
            posix_shell(chan)
        else:
            windows_shell(chan)
    def posix_shell(chan):
        import select
        oldtty = termios.tcgetattr(sys.stdin)
        try:
            tty.setraw(sys.stdin.fileno())
            tty.setcbreak(sys.stdin.fileno())
            chan.settimeout(0.0)
            while True:
                r, w, e = select.select([chan, sys.stdin], [], [])
                if chan in r:
                    try:
                        x = chan.recv(1024)
                        if len(x) == 0:
                            print 'rn*** EOFrn',
                            break
                        sys.stdout.write(x)
                        sys.stdout.flush()
                    except socket.timeout:
                        pass
                if sys.stdin in r:
                    x = sys.stdin.read(1)
                    if len(x) == 0:
                        break
                    chan.send(x)
        finally:
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
    # thanks to Mike Looijmans for this code
    def windows_shell(chan):
        import threading
        sys.stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF.rnrn")
        def writeall(sock):
            while True:
                data = sock.recv(256)
                if not data:
                    sys.stdout.write('rn*** EOF ***rnrn')
                    sys.stdout.flush()
                    break
                sys.stdout.write(data)
                sys.stdout.flush()
        writer = threading.Thread(target=writeall, args=(chan,))
        writer.start()
        try:
            while True:
                d = sys.stdin.read(1)
                if not d:
                    break
                chan.send(d)
        except EOFError:
            # user hit ^Z or F6
            pass

    メインスクリプトssh_inter.py
    # -*- coding:utf-8 -*-
    import paramiko
    import interactive
    #     
    paramiko.util.log_to_file('/tmp/test')
    #   ssh  
    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(
        '10.10.100.71',
        port=22,
        username='root',
        password='cljslrl0620',
        compress=True)
    #      shell  
    channel = ssh.invoke_shell()
    #        
    interactive.interactive_shell(channel)
    #     
    channel.close()
    ssh.close()

    端末実行python ssh_inter.py、効果が見えます.
    pythonモジュールparamikoとsshに感謝します.
    スクリプトを実行するマシンとリモートマシンのshellは、bashなどのshellであることに注意してください.
    七、もっと
    paramiko公式apiドキュメントpythonモジュールparamikoとssh pythonのparamikoモジュールを使用してsshとscp機能を実現