python RPI Externe IP senden

Gast #3459264
Lesenswert?

Moin,

hier gibt es bestimnmt jemand, der mir helfen kann. Vorab: Ich habe von 
python keine Ahnung und werde es auch nicht lernen wollen.

Ich habe unten angehängten Code eingebunden. Es läuft auch. Nur sitzt 
der PI hinter einem Router und ich brauche die externe IP.

Das geht z.B. mit
1
wget -q -O - checkip.dyndns.org | sed -e 's/[^[:digit:]|.]//g'
.

Die Ausgabe ist aaa.bbb.ccc.ddd

Wie bekomme ich die Ausgabe in die Variable ipaddr?



Gruß
Holger





1
import subprocess
2
import smtplib
3
import socket
4
from email.mime.text import MIMEText
5
import datetime
6
# Change to your own account information
7
to = 'me@example.com'
8
gmail_user = 'test@gmail.com'
9
gmail_password = 'yourpassword'
10
smtpserver = smtplib.SMTP('smtp.gmail.com', 587)
11
smtpserver.ehlo()
12
smtpserver.starttls()
13
smtpserver.ehlo
14
smtpserver.login(gmail_user, gmail_password)
15
today = datetime.date.today()
16
# Very Linux Specific
17
arg='ip route list'
18
p=subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE)
19
data = p.communicate()
20
split_data = data[0].split()
21
ipaddr = split_data[split_data.index('src')+1]
22
my_ip = 'Your ip is %s' %  ipaddr
23
msg = MIMEText(my_ip)
24
msg['Subject'] = 'IP For RaspberryPi on %s' % today.strftime('%b %d %Y')
25
msg['From'] = gmail_user
26
msg['To'] = to
27
smtpserver.sendmail(gmail_user, [to], msg.as_string())
28
smtpserver.quit()
#3685043
Lesenswert?

Die communicate() methode gibt ein Tupel zurück. Ersteres ist die 
Standardausgabe des Prozesses, das zweite eine etwaige Fehlermeldung. 
Dabei ist das ganze byte codiert und muss gegebenenfalls decodiert 
werden.

Der Aufuf müsste also so aussehen
1
com_msg, com_err =  p.communicate()
2
if com_err.decode("utf-8") == "error":
3
      raise Exception("Oh noooooooo")
4
if com_msg.decode("utf-8") == "irgendwas":
5
      print(com_msg.decode("utf-8") )

Die hervorragende Python Doku liefert noch mehr Infos.

https://docs.python.org/2/library/subprocess.html#popen-objects

Antwort schreiben

Bitte melde dich an, um einen Beitrag zu schreiben.

oder

Mit Google-Account einloggen

Die Registrierung ist kostenlos und dauert nur eine Minute.

Jetzt registrieren