商务合作加Q:411239339

利用paramiko模块完成sftp和ssh的自动交互

浏览:699次阅读
没有评论

共计 2413 个字符,预计需要花费 7 分钟才能阅读完成。

1、以下是 sftp 的类:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import paramiko
import os,sys
import traceback
class class_remote_sftp:
    def __init__(self,remoteip,username,password,port=22):
        self.remoteip = remoteip
        self.username = username
        self.password = password
        self.port = port
    def sftp_connect(self):
        try:
            t = paramiko.Transport((self.remoteip, self.port))
            t.connect(username = self.username, password = self.password)
            self.sftp = paramiko.SFTPClient.from_transport(t)
        except Exception,e:
            traceback.print_exc()
    def sftp_put(self,remote_path,local_path):
        try:
            self.sftp.put(local_path,remote_path)
        except Exception,e:
            traceback.print_exc()
    def sftp_get(self,remote_path,local_path):
        try:
            self.sftp.get(local_path,remote_path)
        except Exception,e:
            traceback.print_exc()
    def sftp_close(self):
        try:
            self.sftp.close()
        except:
            pass


2、以下是 ssh 类:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import paramiko
import os,sys
import traceback
class class_remote_ssh:
    def __init__(self,remoteip,username,password,port=22):
        self.ssh = paramiko.SSHClient()
        self.remoteip = remoteip
        self.username = username
        self.password = password
        #self.command = command
        self.port = port
    def ssh_connect(self):
        try:
            self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.ssh.connect(self.remoteip, self.port, self.username, self.password)
        except Exception,e:
            traceback.print_exc()
    def ssh_exec_command(self,command):
        try:
            stdin, stdout, stderr = self.ssh.exec_command(command)
            c = stdout.readlines()
            #print c
            return c
        except Exception,e:
                traceback.print_exc()
    def ssh_close(self):
        try:
            self.ssh.close()
        except:
            pass

3、调用方法

以下以连接 192.168.0.1 服务器,将本的地 /home/hell.c 文件传输到服务器的 /tmp/remote.tmp 文件。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import class_ssh
import class_sftp
remoteip='192.168.0.1'
username='root'
password='123456'
port='22'
remote_des_file='/tmp/remote.tmp'
local_des_file='/home/hello.c'
csftp = class_sftp.class_remote_sftp(remoteip,username,password,int(port))
csftp.sftp_connect()
csftp.sftp_put(remote_des_file, local_des_file)

正文完
扫码赞助
post-qrcode
 0
果子
版权声明:本站原创文章,由 果子 于2014-09-05发表,共计2413字。
转载说明:除特殊说明外本站文章皆由果较瘦原创发布,转载请注明出处。
评论(没有评论)