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
Related
I'm creating a very simple HTTP server in python 2 for testing.
I would like to randomly delay by a fixed amount the reply to a GET request without closing the connection to the server or shutting down the server first.
Here is the current code I would like to modify:
# Only runs under Python 2
import BaseHTTPServer
import time
from datetime import datetime
class SimpleRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
print "incoming request: " + self.path
self.wfile.write('HTTP-1.0 200 Okay\r\n\r\n')
self.wfile.write(modes(self.path))
def run(server_class = BaseHTTPServer.HTTPServer,
handler_class = SimpleRequestHandler):
server_address = ('', 80)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
def modes(argument):
# returns value based on time of day to simulate data
curr_time = datetime.now()
seconds = int(curr_time.strftime('%S'))
if seconds < 20:
return "reply1"
elif seconds >= 20 and seconds < 40:
return "reply2"
else:
return "reply3"
run ( )
The delay would be be added every, say, 3rd or 4th time a GET is received but when the delay times out, a properly formed response would be sent.
Thanks.
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.
When I filter the packets using this filter in wireshark:
wlan.sa == 04.b1.67.14.bd.64
All goes perfect.
However, I'm trying to do it with the following python script using scapy, but it never filter by the source mac:
from scapy.all import *
from datetime import datetime
import traceback
# import MySQLdb
def getAverageSSI():
global ssiFinal
return ssiFinal
def setParams():
global window
global timestamp
global SSID
global datetime
global iterator1
window = 1
timestamp = datetime.now()
SSID='DefaultName'
iterator1 = 0
global ssiArray
ssiArray = []
def myPacketHandler(pkt) :
global SSID
global timestamp
global iterator1
global ssiArray
try :
if pkt.haslayer(Dot11) :
ssiNew = -(256-ord(pkt.notdecoded[-4:-3]))
ssiArray.append(ssiNew)
diffT=(datetime.now()-timestamp).seconds
if diffT>window:
print 'With MAC dst = %s with SSI Power= %s' %(pkt.addr1, sum(ssiArray)/len(ssiArray))
print ssiArray
ssiArray = []
timestamp=datetime.now()
except Exception as e:
print 'Exception'
print e
traceback.print_exc()
sys.exit(0)
setParams()
try:
sniff(iface="wlan1", filter="ether src 04:b1:67:14:bd:64", prn = myPacketHandler, store=0)
except Exception as e:
print e
print "Sniff AP1 Off"
I have also tried to remove the filter in sniff, and put an if like the following:
if pkt.addr1 == '04:b1:67:14:bd:64' : # mac xiaomi mi a1
# SSID = pkt.info;
ssiNew = -(256-ord(pkt.notdecoded[-4:-3]))
ssiArray.append(ssiNew)
diffT=(datetime.now()-timestamp).seconds
if diffT>window:
# query = "START TRANSACTION;"
# queryBack=cur.execute(query)
# query = "INSERT INTO RSSI VALUES(%d,\"AP1\",%d);"%(iterator1,ssiNew)
# queryBack = cur.execute(query)
print 'MAC = %s with SSI Power= %s' %(pkt.addr1, sum(ssiArray)/len(ssiArray))
ssiArray = []
# Conexion.commit()
# iterator1+=1
timestamp=datetime.now()
But it is only filtering by destination mac.
Do you know how to properly filter by mac like in the following wireshark image? (it needs to be exactly the same behaviour than in the wireshark filter):
Your second method should be working well, if you used addr2 instead of addr1
Here is how it works in 802.11 (yes it’s really messy)
Also, you should update to the github scapy version, which has support for RSSI directly (so you don’t have to parse notdecoded)
See https://github.com/secdev/scapy/archive/master.zip
This is the code which works well for all AT commands except "FN":
from digi.xbee.devices import XBeeDevice
#Initialise a serial port for the local xbee
local_xbee = XBeeDevice("/dev/tty.usbserial-AH02D9Q4", 9600).
#Opens serial port for sending commands
local_xbee.open()
#Sets new timeout for sync command operation
local.set_sync_ops_timeout(10).
#Send "FN" AT command to local xbee to receive neighbour list
neighbour_xbee_list = local.get_parameter("FN")
print(neighbour_xbee_list)
local_xbee.close()
Note:
The above code returns only one neighbour whereas I have more than one nodes in the network.
I believe the point of the question is not how to use the FN command, but how to discover neighbors.
For this, you can use the start_discovery_process function described here.
http://xbplib.readthedocs.io/en/latest/user_doc/discovering_the_xbee_network.html#discovernetwork
import serial
from digi.xbee.packets.common import ATCommPacket
from digi.xbee.devices import XBeeDevice
from digi.xbee.reader import PacketListener
from digi.xbee.serial import XBeeSerialPort
from digi.xbee.util import utils
import time
local_xbee = XBeeDevice("/dev/tty.usbserial-AH02D9Q4", 9600)
local_xbee.open()
print("This is : ", local_xbee.get_node_id())
print(local_xbee._packet_listener.is_running())
parameter = "FN"
frame_id = 33
my_packet = ATCommPacket(frame_id, parameter)
#print(my_packet)
#print(my_packet.frame_id)
#print(my_packet.command)
final_send = my_packet.output()
local_xbee._serial_port.write(final_send)
print("Finding Neighbours")
while True:
print(".")
Queue = local_xbee._packet_listener.get_queue()
received_packet = Queue.get_by_id(frame_id)
if received_packet != None:
#if received_packet.status == ATCommandStatus.OK:
final = received_packet._get_api_packet_spec_data().__str__()
print(final)
time.sleep(0.5)
local_xbee.close()
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.