您的位置:首页 > 编程语言 > Python开发

Python:paramiko模块

2016-07-06 14:32 351 查看
#!/usr/bin/env python
#coding=utf-8

import os
import paramiko
import datetime

#远程服务器
hostname = '192.168.1.xxx'
port = xxx
username = 'fangyali'
password = 'xxx'
local_dir='/home/fangyali/test'
remote_dir='/tmp/fangyali'

def ssh():
try:
s = paramiko.SSHClient()
#读取know_host
#s.load_system_host_keys()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#建立SSH连接
s.connect(hostname,port,username,password)
stdin,stdout,stderr = s.exec_command('/sbin/ifconfig;free;df -h')
#打印标准输出
print stdout.read()
except Exception,e:
print "error!",e
finally:
s.close()

def upload():
try:
t=paramiko.Transport((hostname,port))
t.connect(username=username,password=password)
sftp=paramiko.SFTPClient.from_transport(t)
#本地使用os模块,远端使用sftp.listdir(remote_dir)
files=os.listdir(local_dir)
for f in files:
print ''
print '#########################################'
print 'Beginning to upload file %s ' % datetime.datetime.now()
print 'Uploading file:',os.path.join(local_dir,f)

#上传put:local-remote,下载get:remote-local
sftp.put(os.path.join(local_dir,f),os.path.join(remote_dir,f))

print 'Upload file success %s ' % datetime.datetime.now()
print ''
print '##########################################'

except Exception,e:
print "error!",e
finally:
t.close()

def download():
try:
t=paramiko.Transport((hostname,port))
t.connect(username=username,password=password)
sftp=paramiko.SFTPClient.from_transport(t)
#本地使用os模块,远端使用sftp.listdir(remote_dir)
files=sftp.listdir(remote_dir)
for f in files:
print ''
print '#########################################'
print 'Beginning to download file from %s %s ' % (hostname,datetime.datetime.now())
print 'Downloading file:',os.path.join(remote_dir,f)

sftp.get(os.path.join(remote_dir,f),os.path.join(local_dir,f))
#上传put:local-remote,下载get:remote-local

print 'Download file success %s ' % datetime.datetime.now()
print ''
print '##########################################'

except Exception,e:
print "error!",e
finally:
t.close()

def download_one():
try:
t=paramiko.Transport((hostname,port))
t.connect(username=username,password=password)
sftp=paramiko.SFTPClient.from_transport(t)
sftp.get("/tmp/fangyali/mysql_status.txt3306","/home/fangyali/test/1.txt")

except Exception,e:
print "error!",e
finally:
t.close()

ssh()
upload()
download()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: