How to check time from internet using bash or python? [duplicate] - python

This question already has answers here:
ntp client in python
(4 answers)
Python Getting date online?
(9 answers)
Closed 5 years ago.
This should be a very simple task, but after 2 hours of searching and reading documents I failed to find a way to check the date and time from the internet using bash or python without installing anything extra like ntplib.
I am basically looking for an equivalent of pythons now() or bash $ date, but using an NTP (or any other way) to get the correct date and time from the internet. All the methods I find (such as ntpd) are meant to correct the system time, which is not my purpose.

Easy way to get the correct time in python
import time
import os
try:
import ntplib
client = ntplib.NTPClient()
response = client.request('pool.ntp.org')
os.system('date ' + time.strftime('%m%d%H%M%Y.%S',time.localtime(response.tx_time)))
except:
print('Could not sync with time server.')
print('Done.')

Related

Send a formated list with pushover on python [duplicate]

This question already has answers here:
How to concatenate (join) items in a list to a single string
(11 answers)
Closed 2 years ago.
I'm relatively new to python,
I built a webscraper that gets the top posts of a website and stores them in a list in python like this:
T = ["post1","post2","post3,"post4"]
To send the push notification with pushover I installed the pushover module that works like this:
from pushover import Pushover
po = Pushover("My App Token")
po.user("My User Token")
msg = po.msg("Hello, World!")
po.send(msg)
I want to send the list as a message with format, like this:
Top Posts:
1. post 1
2. post 2
3. post 3
4. post 4
I tried this:
msg = po.msg("<b>Top Posts:</b>\n\n1. "+T[0]+"\n"+"2. "+T[1]+"\n"+"3. "+T[2]+"\n"+"4. "+T[3]")
The above solution works, however the number of posts will be variable so that's not a viable solution.
What can I do to send the message with the correct formatting knowing that the number of posts in the list will vary from time to time?
Using str.join and a comprehension using enumerate:
msg = po.msg("<b>Top Posts:</b>\n\n" + '\n'.join(f'{n}. s {n}' for n, s in enumerate(T, 1)))

Python switch between users [duplicate]

This question already has answers here:
Is there a portable way to get the current username in Python?
(15 answers)
Closed 2 years ago.
I am trying to implement a switch at the beginning of my code, in order to change the working directory based on who's running the code. In Stata, this exists and looks like the following:
if "`c(username)'" == "albert" {
local PATH "/home/albert/Dropbox/Project1"
}
else if "`c(username)'" == "charlene" {
local PATH "C:/Users/charlene/Documents/Dropbox/Project1"
}
I am just missing the "user" part in python. Does anyone knows if that even exists ?
Would the getpass.getuser() function do the trick?

Python requests with timer and string replace [duplicate]

This question already has answers here:
Print to the same line and not a new line? [duplicate]
(19 answers)
Closed 3 years ago.
I am using an API where I can fetch data with. From the data output I am trying to get specific portions so I can place it nicely in a formatted text.
I want to fetch the data every 5 seconds, so I get fresh info. I do not want that the data is prompted below the output from the first run, but rather replace the current value(s) for the updated value(s).
As I'm pretty bad with python, I hope someone can give me some advice.
import requests
import threading
def dostuff()
threading.Timer(5.0, dostuff).start()
r = requests.get('https://api')
data = r.json()
print("Amount:", data['amount'])
print("Games played:", data['matches'])
dostuff()
This works fine. It just keeps posting the output under each other.
I wish to have everything static, except the data['amount'], and data['matches'], which should keep updating without actually posting it on newlines. I have tried resolving this by clearning the screen, but that is not the desired solution.
Just add end='\r' to your print statement:
import requests
import threading
import random
def dostuff():
threading.Timer(1.0, dostuff).start()
# replaced as actual api not posted
data = {
'amount': round(random.random(), 2),
"matches": round(random.random(), 2)
}
print("Amount: {} Games played: {}".format(
data['amount'],
data['matches']
), end='\r')
dostuff()

Python List all devices on local network, along with ip address [duplicate]

This question already has answers here:
List of IP addresses/hostnames from local network in Python
(11 answers)
Closed 4 years ago.
I'm trying to somehow get a list of all connected devices on a network, and then show their ip with it. I want it to show something like this:
computername - 192.168.0.0
computer2 - 192.168.100.43
I have tried nmap and after a long time I was able to use it but it wont work.
I'm using Python 3.6.5, Windows 8.1.
If anyone could answer, it would help a lot.
Edit: I did go here before, but I'm not sure how to list the names and ip using that method.
You can use the command arp -a and scrape the results of os.popen:
import os, re
full_results = [re.findall('^[\w\?\.]+|(?<=\s)\([\d\.]+\)|(?<=at\s)[\w\:]+', i) for i in os.popen('arp -a')]
final_results = [dict(zip(['IP', 'LAN_IP', 'MAC_ADDRESS'], i)) for i in full_results]
final_results = [{**i, **{'LAN_IP':i['LAN_IP'][1:-1]}} for i in final_results]
Sample output:
[{'IP': '?', 'LAN_IP': '192.168.1.4', 'MAC_ADDRESS': '11:1a:ec:da:d4:ee'}, ...]
arp -a gives a full listing of all the devices on the network of the machine executing the command.

Get just domain name from URL in Python [duplicate]

This question already has answers here:
Extract domain name from URL in Python
(8 answers)
Closed 3 years ago.
I've seen questions similar to this but not really getting at what I'm looking for so I was wondering. I'm trying to extract the main domain of a server from its URL, but just that, without any subdomains. So if the URL was, for example, "http://forums.example.com/" I want to know how to extract just the "example.com" portion from it. I've tried splitting at the second-to-last dot but that brings trouble when dealing with URLs like "http://forums.example.co.uk/", as it extracts just the "co.uk" when I would want "example.co.uk". Is there a way I can parse URLs this way without having to find a list of TLDs to compare?
PS: In case it matters, I will be using this in the context of mail servers, so the URLs will likely look more like "mail.example.co.uk" or "message-ID#user.mail.example.co.uk"
Edit: Okay so I know that the answer to this question is the same as one of the answers in the "duplicate" question but I believe it is different because the questions are different. In the other question the asker was asking regardless of subdomains and so the selected answer used urlparse, which doesn't distinguish subdomain from domain. In addition this question asks about email addresses as well, and urlparse doesn't work on email addresses (throws invalid url exception). So I believe this question is distinct from the other and not a duplicate
You want to check out tldextract. With it you can do everything you want easily. For example:
>>> import tldextract
>>> extracted_domain = tldextract.extract('forums.example.com')
ExtractResult(subdomain='forums', domain='example', suffix='com')
Then you can just:
>>> domain = "{}.{}".format(extracted_domain.domain, extracted_domain.suffix)
>>> domain
'example.com'
It also works with emails:
>>> tldextract.extract('message-ID#user.mail.example.co.uk')
ExtractResult(subdomain='user.mail', domain='example', suffix='co.uk')
Just use pip to install it: pip install tldextract

Categories

Resources