PiUp - Python - Raspberry Pi, IP FTP Upload Script

Forums:

I wanted a way to upload the IP settings from my pi to a website so that I know what the host, IP settings and gateway remotely.
This allows me to set up my router on a specific port and get to the pi.
Nothing overly complicated, just puts the hostname,lan and wan IP and uploads to a web server.
Here is the PiUp.py script with the zip file below. You will have to edit with your own FTP settings.
I added a try/except block around some of the functions for a cleaner output when wifi is down and will try to get them
pasted in sometime. That way instead of an error you get a "gateway not available" message.

You may need to install python 3 or 3.5 else you will get an error message that it cannot process some functions. (fencode if I recall)
I would recommend python3 because installing 3.5 seemed to mess up a few things on my pi like the thonny editor.
3 comes on the pi so I am not sure why I went to 3.5, I probably shouldn't have but did not think it would mess anything up.
-------- To install python3.5 (or greater) on a fresh rasp -------------
1. wget https://www.python.org/ftp/python/3.5.2/Python-3.5.2.tar.xz
2. tar -xvf Python-3.5.2.tar.xz
3. cd Python-3.5.2
4. ./configure
5. make
6 make altinstall
------------- end python install
note: The altinstall I had to run using sudo.

I set up crontab for it to run every hour with crontab -e
0 * * * * python3.5 /home/pi/bin/piup.py # JOB_ID_1

Enjoy.
-------------------------------------------------------- cut PiUp.py ------------------------------------------------------------
#!/usr/bin/python
# -*- coding: utf-8 -*-s
import os # directory methods
import datetime
import sys
import ftplib
import socket
import struct
import fcntl

#------------change settings
ftpU="yourftpuser"
ftpP="yourftppassword"
ftpHost="yourftphost"
pingTarget="google.com"
#-------------------
d=datetime.datetime.now()
now="{0}".format(d).split('.')[0]
y=d.strftime('%Y')
m=d.strftime('%m')
ftpLp=0
ftpLimit=10
workDir = r"/home/pi/bin/work"
os.chdir(workDir)
ftpOn='true'
ftpPath = r"/"

directory = os.fsencode(workDir)
mths=["x","Jan","Feb","Mar","Apr","May","Jun","Jly","Aug","Sep","Oct","Nov","Dec"]
pi_name=socket.gethostname()
#pi_ip=check_output(['hostname', '-I'])

def WriteHtmlFile(htmlfilename,htmlfilebody,title):
writeToFile(htmlfilename,"\n\n{0}".format(htmlfilebody,title), 'false','true')

def ftpFile(filename):
if (ftpOn == 'true'):
try:
cwd = os.getcwd()
ftp = ftplib.FTP(ftpHost)
ftp.login(ftpU, ftpP)
ftp.cwd(ftpPath)
if(cwd != workDir):
os.chdir(workDir)
ftp.storlines("STOR " + filename, open(filename,'rb',1024))
print("[Ftp ok]")
ftp.close()
except:
print("....Ftp failed")
def getArgs():
if (len(sys.argv) > 0):
for argv in sys.argv:
if (argv.split('=')[0]=='m'):
m=argv[1]
if (argv.split('=')[0]=='y'):
y=argv[1]
return
getArgs()
def writeToFile(fileName,data, isbinary, ishtml):
if len(data)>1:
fn= fileName # QtGui.QFileDialog.getSaveFileName(self, "Save file", "", "*.*")with open("test.txt", "a") as myfile:
if ishtml:
with open(fn, "w") as file:
file.write(data)
print("{:d} chars written to {:s}".format(len(data),fn))
else:
with open(fn, "a") as file:
file.write(data)
print("{:d} chars written to {:s}".format(len(data),fn))

else:
print ("No data to save")
ftpPath = r"/"
def getip():
try:
hostname = socket.gethostname()
from subprocess import check_output
ipAll="{0}".format(check_output(['hostname', '-I'])).split(' ')[0].replace('b\'','')
return "{0}\n\n{1}".format(hostname, ipAll)
except:
return "Could not get hostname\n"

rpt = ("\n{0}\n\n{1}\n".format(now,getip()))
#print(rpt)
try:
#get IP
ic=os.popen("ifconfig | grep 'inet'")
l1=ic.read()
rpt = rpt + "{0}\n\n".format(l1.split('\n')[0].split(' ')[0])
except:
rpt = rpt + "Unable to resolve IP"
try:
# max hops ends at router, -n skips name resolution so faster
ir = os.popen("traceroute google.com --max-hops=2 -n")
rOut = ir.read()
rpt = rpt + "{0}\n".format(rOut.split('\n')[2].split(' ')[3])
except:
rpt = rpt + "Unable to resolve Gateway\n"
rpt = rpt +"\n"
piFile="{0}.html".format(pi_name)
WriteHtmlFile(piFile,rpt,pi_name)
print (rpt.replace("","\n"))
ftpFile(piFile)

Pics: 
piup run
PiUp Task
Files: 
AttachmentSize
Package icon PiUp python source code (zipped)1.49 KB
-6.1193329,39.1580149,05-20-2019 02:16:14 AM,!Stopped for gas