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)
- 微信扫码赞助
- 支付宝赞助