下午刚写完的sftp测试代码,没什么好说,都是paramiko模块的教科书式使用,网上代码也很多。测试了一下,传文件基本没问题,0.03s一个,满足项目最低要求(emmm不过传输照片就GG了,一张0.5Mb的照片用了一秒上传)。过几天就准备上无人机测试,希望别炸。讲真还是MQTT协议快一点,不过要开学了暂时也没得搞,有空再琢磨。
#!/usr/bin/python
import paramiko
import time
#Login the server machine,get ready to open sftp
def Login():
t = paramiko.Transport(ip,22)
t.connect(username = name,password = passwd)
return t
#Vargin 'derection' can be 'upload' or 'download'
def Sftp_work(t,derection):
sftp = paramiko.SFTPClient.from_transport(t)
remotepath='/root/myfile/public_file'
localpath='/home/pi/project/MQTTC/public_file'
if derection == "upload":
sftp.put(localpath,remotepath)
print "Upload file to server machine successfully!\n"
if derection == "download":
sftp.get(remotepath,localpath)
print "Download file to local machine successfully!\n"
#Close the sftp
def Logout(t):
t.close()
#Open ssh and sent a command then close it
def Sent_Command(Command):
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect(ip,22,name, passwd)
stdin, stdout, stderr = s.exec_command(Command)
print stdout.readlines()
s.close()
ip = "xxx.xxx.xxx.xxx"
name = "root"
passwd = "xxxxxxxx"
#Just for test
Sent_Command("echo 'hello world'")
#main to decide 'upload' or 'download'
start=time.clock()
tp = Login()
atlog=time.clock()
Sftp_work(tp,'upload')
atup=time.clock()
Sftp_work(tp,'download')
atdown=time.clock()
Logout(tp)
atlogt=time.clock()
print "Upload Time:"+str(atup-atlog)+'\n'
print "Download Time:"+str(atdown-atup)+'\n'
print "Total Time:"+str(atlogt-start)+'\n'
这两天现学现玩的蛇,有空再来优化了。慢慢学习。