haishi 发表于 2018-8-16 09:13:04

Python 学习笔记 - Paramiko 模块

import paramiko  
import uuid
  
class SSHConnection(object):
  

  
    #初始化封装字段
  
    def __init__(self, host='sydnagios', port=22, username='root',pwd='123'):
  
      self.host = host
  
      self.port = port
  
      self.username = username
  
      self.pwd = pwd
  
      self.__k = None
  
    #连接session,执行操作,断开session
  
    def run(self):
  
      self.connect()
  
      pass
  
      self.close()
  
    #连接
  
    def connect(self):
  
      transport = paramiko.Transport((self.host,self.port))
  
      transport.connect(username=self.username,password=self.pwd)
  
      self.__transport = transport
  
    #断开
  
    def close(self):
  
      self.__transport.close()
  

  
    #执行命令
  
    def cmd(self, command):
  
      ssh = paramiko.SSHClient()
  
      ssh._transport = self.__transport
  
      # 执行命令
  
      stdin, stdout, stderr = ssh.exec_command(command)
  
      # 获取命令结果
  
      result = stdout.read()
  
      return result
  
    def upload(self,local_path, target_path):
  
      # 连接,上传
  
      sftp = paramiko.SFTPClient.from_transport(self.__transport)
  
      # 将location.py 上传至服务器 /tmp/test.py
  
      sftp.put(local_path, target_path)
  
ssh = SSHConnection()
  
ssh.connect()
  
r1 = ssh.cmd('df')
  
print(r1.decode())
  
ssh.upload('c:\\temp\\aaa.txt', "/home/yli/s7.py")
  
ssh.close()
  
----------
  
"C:\Program Files\Python3\python.exe" C:/s13课上代码/s13day13课上代码/s13day13_课上代码/paramiko模块_demo.py
  
Filesystem            1K-blocks    Used Available Use% Mounted on
  
/dev/mapper/centos-root28813572 67607322205284024% /
  
devtmpfs                  1011616       0   1011616   0% /dev
  
tmpfs                     1021272      80   1021192   1% /dev/shm
  
tmpfs                     1021272113928    90734412% /run
  
tmpfs                     1021272       0   1021272   0% /sys/fs/cgroup
  
/dev/sda1                  508588172604    33598434% /boot
  
tmpfs                      204256      12    204244   1% /run/user/42
  
tmpfs                      204256       0    204256   0% /run/user/0


页: [1]
查看完整版本: Python 学习笔记 - Paramiko 模块