12
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

paramikoでSSH通信するまで

Last updated at Posted at 2018-04-11

インストールからParamikoでSSH通信するまでのメモ、
Python及びpipを使ったことなかったので、基本的にな部分からメモを残す。

pipへの環境変数追加

Python/Scriptを環境変数に追加。

Paramikoのインストール

プロキシ環境下での作業だったので、以下のcommandによりinstallを行う。

pip install --proxy=http://[username]:[Pass]@[proxy]:[port] paramiko

実装

Paramiko自体の使い方は以下のサイトを参考にさせていただいた。
https://qiita.com/ototo/items/cc1bc7b83f0722dfd5ca

以下のようにクラスを作成。

# coding: utf-8

import paramiko
import time

class SSHConnector:
    __hostName = ''
    __userName = ''
    __password = ''
    __port = ''
    __ssh = None

    def __init__(self,hostName,userName,password,port):    
        self.__hostName = hostName
        self.__userName = userName
        self.__password = password
        self.__port = port
        self.__initSSH()
        
    def __del__(self):
        self.__ssh.close()
        
    def __initSSH(self):
        self.__ssh = paramiko.SSHClient()
        self.__ssh.load_system_host_keys()
        self.__ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.__ssh.connect(self.__hostName, username=self.__userName, password=self.__password, port=self.__port, timeout=15.0,look_for_keys=False)
        
        
    def sendMessage(self,command):
        ssh_shell = self.__ssh.invoke_shell()
        ssh_shell.send(command)
        time.sleep(3)
        resultMessage = ''
        if (ssh_shell.recv_ready()):
            resultMessage += ssh_shell.recv(9999)
            resultMessage += '\r\n'
        else:
            print 'error'
           
        return resultMessage 

さいごに

ざっと書いては見たものの、Pythonの書き方も不慣れなため、Gitとか見てもう少し勉強すべき。

12
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?