码迷,mamicode.com
首页 > 编程语言 > 详细

Python paramiko

时间:2016-09-24 12:13:56      阅读:338      评论:0      收藏:0      [点我收藏+]

标签:

paramiko有两个模块SSHClient()和SFTPClient()

利用SSHClient()

#coding:utf-8
import paramiko

#创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname=192.168.2.103, port=22, username=root, password=123456)

# 执行命令
stdin, stdout, stderr = ssh.exec_command(ls)
# 获取命令结果
result = stdout.read()
print (str(result,encoding=utf-8))
# 关闭连接
ssh.close()

SSHClient()里面有一个transport变量,这个是用于获取连接的,因此我们也可以单独的获取到transport变量,然后执行连接操作

#coding:utf-8
import paramiko

transport = paramiko.Transport((192.168.2.103, 22))
transport.connect(username=root, password=123456)

ssh = paramiko.SSHClient()
ssh._transport = transport

stdin, stdout, stderr = ssh.exec_command(df)
print (str(stdout.read(),encoding=utf-8))

transport.close()

SFTPClient()也是使用transport来实现的,因此如果有需求需要执行命令和上传文件糅合在一起的话,那么就需要使用transport的方式来实现。

用transport实现上传下载以及命令的执行:

#coding:utf-8
import paramiko
import uuid

class SSHConnection(object):

    def __init__(self, host=192.168.2.103, port=22, username=root,pwd=123456):
        self.host = host
        self.port = port
        self.username = username
        self.pwd = pwd
        self.__k = None

    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 upload(self,local_path,target_path):
        # 连接,上传
        # file_name = self.create_file()
        sftp = paramiko.SFTPClient.from_transport(self.__transport)
        # 将location.py 上传至服务器 /tmp/test.py
        sftp.put(local_path, target_path)

    def download(self,remote_path,local_path):
        sftp = paramiko.SFTPClient.from_transport(self.__transport)
        sftp.get(remote_path,local_path)

    def cmd(self, command):
        ssh = paramiko.SSHClient()
        ssh._transport = self.__transport
        # 执行命令
        stdin, stdout, stderr = ssh.exec_command(command)
        # 获取命令结果
        result = stdout.read()
        print (str(result,encoding=utf-8))
        return result

ssh = SSHConnection()
ssh.connect()
ssh.cmd("ls")
ssh.upload(s1.py,/tmp/ks77.py)
ssh.download(/tmp/test.py,kkkk,)
ssh.cmd("df")
ssh.close()

 

Python paramiko

标签:

原文地址:http://www.cnblogs.com/python-study/p/5898445.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!