Python:paramiko模块

来源:互联网 发布:黄子韬微博故事软件 编辑:程序博客网 时间:2024/05/18 03:48


#!/usr/bin/env python  #coding=utf-8import os  import paramiko  import datetime #远程服务器  hostname = '192.168.1.xxx'  port = xxxusername = '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()





0 0