aws lambda python socket issue - python

import time
import datetime
import socket
import ssl
all_ip = ["cert-name1", "cert-name2","cert-name3","cert-name4"]
def ssl_expiry_datetime(hostname):
ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'
context = ssl.create_default_context()
conn = context.wrap_socket(
socket.socket(socket.AF_INET),
server_hostname=hostname,
)
conn.connect((hostname, 443))
ssl_info = conn.getpeercert()
# parse the string from the certificate into a Python datetime object
today_date = time.strftime(r'%b %d %H:%M:%S %Y %Z')
b = datetime.datetime.strptime(ssl_info['notAfter'], ssl_date_fmt)
print b - datetime.datetime.utcnow()
def lambda_handler(event,context):
for hostname in all_ip:
ssl_expiry_datetime(hostname)
My code was this ,if i pass 3 certs it was working but when i add my 4th cert in that list i was getting time out error from 4th cert!!1 amy i doing anything wrong in my code?
Please help, thanks.

Related

How to fetch date and time from internet [duplicate]

I need to get the time for the UK from an NTP server. Found stuff online however any time I try out the code, I always get a return date time, the same as my computer. I changed the time on my computer to confirm this, and I always get that, so it's not coming from the NTP server.
import ntplib
from time import ctime
c = ntplib.NTPClient()
response = c.request('uk.pool.ntp.org', version=3)
response.offset
print (ctime(response.tx_time))
print (ntplib.ref_id_to_text(response.ref_id))
x = ntplib.NTPClient()
print ((x.request('ch.pool.ntp.org').tx_time))
This will work (Python 3):
import socket
import struct
import sys
import time
def RequestTimefromNtp(addr='0.de.pool.ntp.org'):
REF_TIME_1970 = 2208988800 # Reference time
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
data = b'\x1b' + 47 * b'\0'
client.sendto(data, (addr, 123))
data, address = client.recvfrom(1024)
if data:
t = struct.unpack('!12I', data)[10]
t -= REF_TIME_1970
return time.ctime(t), t
if __name__ == "__main__":
print(RequestTimefromNtp())
The timestamps returned as call to the NTP server returns time in seconds.
ctime() provides datetime format based on local machine's timezone settings by default. Thus, for uk timezone you need to convert tx_time using that timezone. Python's in-built datetime module contains function for this purpose
import ntplib
from datetime import datetime, timezone
c = ntplib.NTPClient()
# Provide the respective ntp server ip in below function
response = c.request('uk.pool.ntp.org', version=3)
response.offset
print (datetime.fromtimestamp(response.tx_time, timezone.utc))
UTC timezone used here. For working with different timezones you can use pytz library
This is basically Ahmads answer but working for me on Python 3. I am currently keen on Arrow as simplifying times and then you get:
import arrow
import socket
import struct
import sys
def RequestTimefromNtp(addr='0.de.pool.ntp.org'):
REF_TIME_1970 = 2208988800 # Reference time
client = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
data = b'\x1b' + 47 * b'\0'
client.sendto( data, (addr, 123))
data, address = client.recvfrom( 1024 )
if data:
t = struct.unpack( '!12I', data )[10]
t -= REF_TIME_1970
return arrow.get(t)
print(RequestTimefromNtp())
The following function is working well using python 3:
def GetNTPDateTime(server):
try:
ntpDate = None
client = ntplib.NTPClient()
response = client.request(server, version=3)
ntpDate = ctime(response.tx_time)
print (ntpDate)
except Exception as e:
print (e)
return datetime.datetime.strptime(ntpDate, "%a %b %d %H:%M:%S %Y")
I used ntplib server and get date and change format in dd-mm-yyyy

Setting the time in unix with python from server

I'm trying to set the time in linux with python. I got the date and time , what i need to do the set the time that i got in my system?
import os
import ntplib
from datetime import datetime,timezone
c = ntplib.NTPClient()
response = c.request('ch.pool.ntp.org',version = 3)
response.offset
data = datetime.fromtimestamp(response.tx_time, timezone.utc)
time = data.time()
date = data.date()
time1 =time.strftime("%H:%M:%S")
os.system('date --set %s' % date)
This is the code i wrote to get the time from a server .
in bold it's what i tried and it not working.
Something like this:
import os
# TOOD use real date
rv = os.system('date -s "2 OCT 2006 18:00:00"')
if rv == 0:
print('date was set')
else:
print('date was not set')
Or you can configure your linux to use NTP server.

How to fetch the SSL certificate to see whether it's expired or not

I am not getting any output from this code.The good thing is that i am not getting any error.Please tell me where i am doing wrong.Here is my Code or any alternative way to find the expired date of the ssl certificate(using Python only)
import datetime
import logging
import socket
import ssl
YOUR_DOMAIN = 'google.com'
WARNING_BUFFER = 14
logger = logging.getLogger()
logger.setLevel(logging.INFO)
ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'
class AlreadyExpired(Exception):
pass
def ssl_expires_in(hostname, buffer_days=14):
"""Gets the SSL cert from a given hostname and checks if it expires within buffer_days"""
context = ssl.create_default_context()
conn = context.wrap_socket(
socket.socket(socket.AF_INET),
server_hostname=hostname,
)
# 3 second timeout because Lambda has runtime limitations
conn.settimeout(3.0)
conn.connect((hostname, 443))
ssl_info = conn.getpeercert()
expires = datetime.datetime.strptime(ssl_info['notAfter'], ssl_date_fmt)
# if the cert expires in less than two weeks, we should reissue it
if expires < (datetime.datetime.utcnow() + datetime.timedelta(days=buffer_days)):
# expires sooner than the buffer
return True
elif expires < datetime.datetime.utcnow():
# cert has already expired - uhoh!
raise AlreadyExpired("Cert expired at %s" % ssl_info['notAfter'])
else:
# everything is fine
return False
def lambda_handler(event, context):
try:
if not ssl_expires_in(YOUR_DOMAIN, WARNING_BUFFER):
logger.info("SSL certificate doesn't expire for a while - you're set!")
return {"success": True, "cert_status": "valid"}
else:
logger.warning("SSL certificate expires soon")
return {"success": True, "cert_status": "expiring soon"}
except AlreadyExpired as e:
logger.exception("Certificate is expired, get worried!")
return {"success": True, "cert_status": "expired"}
except Exception as e:
logger.exception("Failed to get certificate info")
return {"success": False, "cert_status": "unknown"}
You can do it with "pyOpenSSL"(pip install pyOpenSSL) and "ssl"(inbuilt in python) packages.
import ssl
import OpenSSL
def get_SSL_Expiry_Date(host, port):
cert = ssl.get_server_certificate((host, port))
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
print(x509.get_notAfter())
get_SSL_Expiry_Date("google.com", 443)
Output: b'20181113080500Z'
Or you can do it only with python like this:
import ssl
import socket
import datetime
def ssl_expiry_datetime(host, port=443):
ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'
context = ssl.create_default_context()
conn = context.wrap_socket(
socket.socket(socket.AF_INET),
server_hostname=host,
)
# 3 second timeout because Lambda has runtime limitations
conn.settimeout(3.0)
conn.connect((host, port))
ssl_info = conn.getpeercert()
print(ssl_info)
# parse the string from the certificate into a Python datetime object
res = datetime.datetime.strptime(ssl_info['notAfter'], ssl_date_fmt)
return res
print(ssl_expiry_datetime("google.com"))
Output: 2018-11-13 08:04:00

Change localtime from UTC to UTC + 2 in python

How I can change this code from localtime UTC to UTC+2. Now hours() function print 13 but I need to write 15.
import time;
def hours():
localtime = time.localtime(time.time())
return localtime.tm_hour
def minutes():
localtime = time.localtime(time.time())
return localtime.tm_min
def seconds():
localtime = time.localtime(time.time())
return localtime.tm_sec
print(hours())
#minutes()
#seconds()
How about using the datetime module:
import datetime;
today = datetime.datetime.now()
todayPlus2Hours = today + datetime.timedelta(hours=2)
print(todayPlus2Hours)
print(todayPlus2Hours.hour)
print(todayPlus2Hours.minute)
print(todayPlus2Hours.second)
You can use pytz along with datetime modules.
for a timezone reference i'd look here.
I'd do something of this sort:
import datetime
import pytz
utc_dt = datetime.datetime.now(tz=pytz.utc)
amsterdam_tz = pytz.timezone("Europe/Amsterdam")
local_amsterdam_time = amsterdam_tz.normalize(utc_dt)
print local_amsterdam_time.hour
print local_amsterdam_time.minute
print local_amsterdam_time.second

Convert Time Zone + format in Python from Twitter API

In Python, with TwitterSearch, I'm able to get the timestamp of the tweet in UTC time, in the following format :
Thu Mar 19 12:37:15 +0000 2015
However, I would like to obtain it automatically in the EST timezone (UTC - 4), in this format :
2015-03-19 08:37:15
Here is a sample of my code. What should I change in it for an automatic conversion?
for tweet in ts.search_tweets_iterable(tso):
lat = None
long = None
user = tweet['user']['screen_name']
user_creation = tweet['user']['created_at']
created_at = tweet['created_at'] # UTC time when Tweet was created.
favorite = tweet['favorite_count']
retweet = tweet ['retweet_count']
id_status = tweet['id']
in_reply_to = tweet['in_reply_to_screen_name']
followers = tweet['user']['followers_count'] # nombre d'abonnés
statuses_count = tweet['user']['statuses_count'] # nombre d'abonnés
location = tweet['user']['location'] # résidence du twittos
tweet_text = tweet['text'].strip() # deux lignes enlèvent espaces inutiles
tweet_text = ''.join(tweet_text.splitlines())
print i,created_at,user_creation,user, tweet_text
if tweet['geo'] and tweet['geo']['coordinates'][0]:
lat, long = tweet['geo']['coordinates'][:2]
print u'#%s: %s' % (user, tweet_text), lat, long
else:
print u'#%s: %s' % (user, tweet_text)
print favorite,retweet,id_status,in_reply_to,followers,statuses_count,location
writer.writerow([user.encode('utf8'), user_creation.encode('utf8'), created_at.encode('utf8'),
tweet_text.encode('utf8'), favorite, retweet, id_status, in_reply_to, followers, statuses_count, location.encode('utf8'), lat, long])
i += 1
if i > max:
return()
Thank you in advance!
Florent
If EST is your local timezone then you could do it using only stdlib:
#!/usr/bin/env python
from datetime import datetime
from email.utils import parsedate_tz, mktime_tz
timestamp = mktime_tz(parsedate_tz('Thu Mar 19 12:37:15 +0000 2015'))
s = str(datetime.fromtimestamp(timestamp))
# -> '2015-03-19 08:37:15'
It supports non-UTC input timezones too.
Or you could specify the destination timezone explicitly:
import pytz # $ pip install pytz
dt = datetime.fromtimestamp(timestamp, pytz.timezone('US/Eastern'))
s = dt.strftime('%Y-%m-%d %H:%M:%S')
# -> '2015-03-19 08:37:15'
You could put it in a function:
#!/usr/bin/env python
from datetime import datetime
from email.utils import parsedate_tz, mktime_tz
def to_local_time(tweet_time_string):
"""Convert rfc 5322 -like time string into a local time
string in rfc 3339 -like format.
"""
timestamp = mktime_tz(parsedate_tz(tweet_time_string))
return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
time_string = to_local_time('Thu Mar 19 12:37:15 +0000 2015')
# use time_string here..
Remove the +0000 from the date sent by twitter and do something like:
from datetime import datetime
import pytz
local = 'Europe/London' #or the local from where twitter date is coming from
dt = datetime.strptime("Thu Mar 19 12:37:15 2015", "%a %b %d %H:%M:%S %Y")
dt = pytz.timezone(local).localize(dt)
est_dt = dt.astimezone(pytz.timezone('EST'))
print est_dt.strftime("%Y-%m-%d %H:%M:%S")
Output:
2015-03-19 07:37:15
Alternatively you can do something like (in this case you don't need to remove the +0000 timezone info):
from dateutil import parser
dt = parser.parse("Thu Mar 19 12:37:15 +0000 2015")
est_dt = dt.astimezone(pytz.timezone('EST'))
print est_dt.strftime("%Y-%m-%d %H:%M:%S")
Output
2015-03-19 07:37:15
By the way, EST is UTC-4 or UTC-5?

Categories