基于ssh协议传输文件例子

使用python模块:paramiko,optparse

__author__ = 'Administrator'
import paramiko
import sys
from optparse import OptionParser
import os
def exit_code(code):
os.system('pause')
sys.exit(code)
def uploadfile(localfile,ip):
if not os.path.exists(localfile):
print '%s not exists!' % localfile
exit_code(10)
root_path = '/root/'
remotefile = os.path.basename(localfile)
t = paramiko.Transport((ip,22))
t.connect(username='root',password='yunwei')
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put(localfile,'%s%s'%(root_path,remotefile))
t.close()
def main():
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option("-f", "--file", dest="file",
help="file path for transport")
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose")
parser.add_option("-H", "--Host", dest='ip',help="the ip address of remote host")
(options,args) = parser.parse_args()
if options.verbose:
print "reading %s..." % options.file
if not options.file or not options.ip:
parser.error("incorrect number of argument!")
exit_code(10)
uploadfile(options.file,options.ip)

if __name__ == "__main__":
main()

posted @ 2015-07-07 13:59  xiewb  阅读(399)  评论(0编辑  收藏  举报