1. 程式人生 > >python ssh之paramiko模塊使用

python ssh之paramiko模塊使用

begin mman strip() 執行命令 shc 顯示錯誤 stdout pac toad

1.安裝:

sudo pip install paramiko

2.連接到linux服務器

方法一:

#paramiko.util.log_to_file(‘ssh.log‘) #寫日誌文件
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #允許連接不在~/.ssh/known_hosts文件中的主機
client.connect(‘ip‘,22, ‘username‘,‘password‘)  #指定ip地址,端口,用戶名和密碼進行連接

方法二:

transport = paramiko.Transport((‘ip‘, port)) #獲取連接
transport.connect(username=‘username‘,password=‘password‘)
ssh = paramiko.SSHClient()
ssh._transport = transport

3.用transport實現上傳下載以及命令的執行

# coding=utf-8
import paramiko

class SSHConnection(object):
    def __init__(self, host, port, username, password):
        self._host = host
        self._port = port
        self._username = username
        self._password = password
        self._transport = None
        self._sftp = None
        self._client = None
        self._connect()  # 建立連接

     def _connect(self):
        transport = paramiko.Transport((self._host, self._port))
        transport.connect(username=self._username, password=self._password)
        self._transport = transport

    #下載
    def download(self, remotepath, localpath):
        if self._sftp is None:
            self._sftp = paramiko.SFTPClient.from_transport(self._transport)
        self._sftp.get(remotepath, localpath)

    #上傳
    def put(self, localpath, remotepath):
        if self._sftp is None:
            self._sftp = paramiko.SFTPClient.from_transport(self._transport)
        self._sftp.put(localpath, remotepath)

    #執行命令
    def exec_command(self, command):
        if self._client is None:
            self._client = paramiko.SSHClient()
            self._client._transport = self._transport
        stdin, stdout, stderr = self._client.exec_command(command)
        data = stdout.read()
        if len(data) > 0:
            print data.strip()   #打印正確結果
            return data
        err = stderr.read()
        if len(err) > 0:
            print err.strip()    #輸出錯誤結果
            return err

    def close(self):
        if self._transport:
            self._transport.close()
        if self._client:
            self._client.close()


if __name__ == "__main__":
    conn = SSHConnection(‘192.168.87.200‘, 22, ‘username‘, ‘password‘)
    localpath = ‘hello.txt‘
    remotepath = ‘/home/hupeng/WorkSpace/Python/test/hello.txt‘
    print ‘downlaod start‘
    conn.download(remotepath, localpath)
    print ‘download end‘
    print ‘put begin‘
    conn.put(localpath, remotepath)
    print ‘put end‘

    conn.exec_command(‘whoami‘)
    conn.exec_command(‘cd WorkSpace/Python/test;pwd‘)  #cd需要特別處理
    conn.exec_command(‘pwd‘)
    conn.exec_command(‘tree WorkSpace/Python/test‘)
    conn.exec_command(‘ls -l‘)
    conn.exec_command(‘echo "hello python" > python.txt‘)
    conn.exec_command(‘ls hello‘)  #顯示錯誤信息
    conn.close()

python ssh之paramiko模塊使用