传输文件

import paramiko
import os

def download_from(ip,u,p):
  file_list=['file2',file3','file4']
  file_path="/home/projs/"
  client=paramiko.Transport((ip,22))
  client.connect(username=u,password=p)
  sftp=paramiko.SFTPClient.from_transport(client)

  for file in file_list:
    sftp.get(os.path.join(file_path,file),os.path.join('local_path',file))
  client.close()

def put_to(ip,u,p):
  file_path="E:\\"
  remote_path='/home/ubuntu/'
  client=paramiko.Transport((ip,22))
  client.connect(username=u,password=p)
  sftp=paramiko.SFTPClient.from_transport(client)
  for file in os.listdir(file_path):
    file_s=os.path.join(file_path,file)
    if os.path.isfile(file_s):
      sftp.put(file_s,os.path.join(remote_path,file))

  client.close()

下载文件使用sftp.get

sftp.get(远程服务器上文件地址,本地保存地址)

上传文件使用sftp.put(本地文件路径,需要传到的远程服务器文件路径)

 

通过ssh连接服务器

ssh = paramiko.SSHClient()

#这里是设置第一次连接的服务器IP时,自动添加可信任host

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# server的格式为{'hostname':'192.xxx.xxx.xx','port':22,'username':'root','password':'xxxxx'}

ssh.connect(**server)

transport_ = ssh.get_transport()

#这里生成的sftp和上面性质一样,可用于文件传输

sftp = transport_.open_sftp_client()

#sftp也可直接读写远程服务器上的文件,sftp.file返回的是一个Python中的类file类的文件对象,大部分对file的操作也可用于stfp.file

with sftp.file('remote/file/path','r') as f:
    txt = f.read()

with sftp.file('/some/remote/file/path','w') as f:
    f.write('some contents..')

#通过ssh.exec_command直接在远程服务器上执行指令

stdin,stdout,stderr = ssh.exec_command("service iptables restart")

logger.warning('stdout:%s,stderr:%s'%(stdout.read(),stderr.read())

ssh.close()

#切记用完后关闭ssh.close(),不关闭可能造成无法想象的结果

 

ssh.connect(**server) 和ssh.close()可以配合使用,打开,关闭;

一个已创建的ssh = paramiko.SSHClient()可以多次 打开再关闭,用于不同服务器的连接

 posted on 2019-03-04 18:20  庭明  阅读(473)  评论(0编辑  收藏  举报