Print Header Information for Human Readability in Python - python

I learned and code below which gives the Hostnames and Its IP address by the reading the hostname from the "mylabList.txt" file, Now i am looking the way to print the output in a pretty Human readable from Like Column header at the top of each and then the name (Below that)..
Is there way to set width between columns while printing...
#!/usr/bin/python
import sys
import socket
with open("mylabList.txt", 'r') as f:
for host in f:
print("{0[0]}\t{0[2][0]}".format(socket.gethostbyname_ex(host.rstrip())))
Current output is Like:
mylab1.example.com 172.10.1.1
mylab2.example.com 172.10.1.2
mylab3.example.com 172.10.1.3
mylab4.example.com 122.10.1.4
Expected Output is:
Server Name IP ADDRESS
===================================
mylab1.example.com 172.10.1.1
mylab2.example.com 172.10.1.2
mylab3.example.com 172.10.1.3
mylab4.example.com 122.10.1.4
Just a note.. in my output Srever Name's lenghth is upto 30 Char long.

You could use ljust and rjust
http://www.tutorialspoint.com/python/string_ljust.htm
http://www.tutorialspoint.com/python/string_rjust.htm
print("A String".ljust(30, " ") + "Another String")
results in
A String Another String
This is a possible way to do the trick:
#!/usr/bin/python
import sys
import socket
print("Server Name".ljust(30, " ") + "IP ADRESS")
print("="*39)
with open("mylabList.txt", 'r') as f:
for host in f:
print("{0[0]}\t{0[2][0]}".format(socket.gethostbyname_ex(host.rstrip())))

Related

Convert Bitcoin private key from file text

Good afternoon, friends, I just started learning python, I found this code that suits my needs, but on the way out everything is synchronized in one line, help me with this problem.
"
import ecdsa
import hashlib
import base58
with open("my_private_key.txt", "r") as f: #Input file path
for line in f:
#Convert hex private key to bytes
private_key = bytes.fromhex(line)
#Derivation of the private key
signing_key = ecdsa.SigningKey.from_string(private_key, curve=ecdsa.SECP256k1)
verifying_key = signing_key.get_verifying_key()
public_key = bytes.fromhex("04") + verifying_key.to_string()
#Hashes of public key
sha256_1 = hashlib.sha256(public_key)
ripemd160 = hashlib.new("ripemd160")
ripemd160.update(sha256_1.digest())
#Adding prefix to identify Network
hashed_public_key = bytes.fromhex("00") + ripemd160.digest()
#Checksum calculation
checksum_full = hashlib.sha256(hashlib.sha256(hashed_public_key).digest()).digest()
checksum = checksum_full[:4]
#Adding checksum to hashpubkey
bin_addr = hashed_public_key + checksum
#Encoding to address
address = str(base58.b58encode(bin_addr))
final_address = address[2:-1]
print(final_address)
with open("my_addresses.txt", "a") as i:
i.write(final_address)
"
print writes a trailing newline after writing all its arguments. write does not; you have to supply it yourself.
with open("my_addresses.txt", "a") as i:
i.write(final_address + "\n")
Or, you can use print:
with open("my_addresses.txt", "a") as i:
print(final_address, file=i)
Ignoring many of its keyword arguments, print is defined something like
def print(*args, end='\n', sep=' ', file=sys.stdout):
file.write(sep.join(args))
file.write(end)
Also, note that you don't need to repeatedly open your output file. You can open it at the same time as the input and leave it open for the duration of the loop.
with open("my_private_key.txt", "r") as f, \
open("my_addresses.txt", "a") as i:
for line in f:
...
print(final_address, file=i)

Python/regex: Change 4th Octet of all IP addresses in a file to .0

I have been battling with this for over a day now; haven't done Python for 3 years now and its showing!
I want the code to work through the file and using substitute I want to change the last octet of each IP address to 0. The re sub line just isn't working and instead of the IP address I get the following in the output file:
<_sre.SRE_Match object at 0x000000000342D718>0
Which is the regex match object plus the 0 that I want as the last octet.
And the code....
import fileinput
import re, sys, os
file1 = 'output.txt'
ipv4Regex = re.compile(r'[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')
def Octet_4_0():
for line in fileinput.input():
line = ipv4Regex.sub(str(re.search(ipv4Regex,line))+'.'.join(ipv4Regex.split('.')[:-1]+["0"]), line.strip())
#print(line)
with open(file1, 'a') as f:
f.write(line+'\n')
fileinput.close()
print "Current working dir : %s" % os.getcwd()
if __name__ == "__main__":
# Delete the previous file
try:
os.remove(file1)
except OSError:
pass
# Run the function
Octet_4_0()
I suggest keeping it simple and just match all IP addresses with the help of a capture group:
ip = 'some text here 127.123.456.789 blah blah'
ip_out = re.sub(r'\b(\d+\.\d+\.\d+)\.\d+\b', r'\1.0', ip)
print(ip_out) # some text here 127.123.456.0 blah blah

String Formatting in Python/Thunderbird

Noob, trying to use Thunderbird (rather than SMTP) to send personalized emails to a few dozen people. I am basically looking to have the message display in Thunderbird as follows:
Dear Bob,
It was nice to meet you the other day.
However, I instead end up with:
Dear Bob (comma missing, and rest of body missing)
I have tried the following:
import subprocess
import os
def send_email(name, email_address):
#print(name, email_address)
os.system("thunderbird -compose to= 'to',subject='subject',body='body'")
tbirdPath = r'c:\Program Files (x86)\Mozilla Thunderbird\thunderbird.exe'
to = email_address
subject = 'Test Subject LIne'
#body = "Dear %s, \n\n This is the body." %(name)
body = 'html><body>Dear %s, This is the body <br></body></html>'%(name)
composeCommand = 'format=html,to={},subject={},body={}'.format(to, subject, body)
subprocess.Popen([tbirdPath, '-compose', composeCommand])
As always, simple answers I can implement are preferred to complex ones I cannot. I suspect I'm missing something stupid about string formatting, but am unsure as to exactly what. Thanks in advance for your help.
From this example, you may need to surround the arguments with single and double quotes.
Like this:
composeCommand = '"format=html,to=\'{}\',subject=\'{}\',body=\'{}\'"'.format(to, subject, body)
By the way, if you are using python 3.6+, using f-strings makes str more readable:
body = f'<html><body>Dear {name}, This is the body <br></body></html>'
composeCommand = f'"format=html,to=\'{to}\',subject=\'{subject}\',body=\'{body}\'"'
So here is a simple program to read in names and email addresses from a CSV file, and to automate drafting emails from your Thunderbird client (you will still need to hit send on each), using Python on a Windows machine.
import csv
import subprocess
import os
# a list that will contain OrderedDict ('Name', 'Bob'), ('email', bob#yahoo.com)
each_persons_info = []
def load_email_info(data_file):
"""
Load data from CSV files into memory.
"""
# Load people
with open(f"email_list.csv", encoding="utf-8") as f:
reader = csv.DictReader(f)
# using DictReader, starts reading at row 2, with row 1 forming your labels, append to each_persons_info list (differs from csv reader in that respect)
for row in reader:
each_persons_info.append(row)
def send_email(name, email_address):
"""
Launches Thunderbird and drafts personalized emails to people on your list, using content you supply in subject and body fields below.
"""
subject = 'Test Subject LIne'
body = "Dear {}".format(name) + '\n' + '\n' + "This is the body." + '\n' + '\n' + "The End." + '\n'
to = email_address
os.system("thunderbird -compose to= 'to',subject='subject',body='body'")
tbirdPath = r'c:\Program Files (x86)\Mozilla Thunderbird\thunderbird.exe'
composeCommand = "format=html,to={},subject={},body='{}'".format(to, subject, body)
subprocess.Popen([tbirdPath, '-compose', composeCommand])
def main():
load_email_info("email_list.csv")
# walk each person through the send email function
for item in each_persons_info:
send_email(name, email_address)
if __name__ == "__main__":
main()

Using a txt file to define multiple variables in python

Background Information
I have a program that I'm using for pinging a service and printing the results back to a window. I'm currently trying to add to this program, by adding a kind of 'settings' file that users can edit to change the a) host that is pinged and b) timeout
What I've tried so far
file = open("file.txt", "r")
print (file.read())
settings = file.read()
# looking for the value of 'host'
pattern = 'host = "(.*)'
variable = re.findall(pattern, settings)[0]
print(test)
As for what is contained within the file.txt file:
host = "youtube.com"
pingTimeout = "1"
However, my attempts have been unsuccessful as this comes up with the following
error:
IndexError: list index out of range
And so, my question is:
Can anyone point me in the right direction to do this? To recap, I am asking how I can take an input from file (in this case host = "youtube.com" and save that as a variable 'host' within the python file).
First, as Patrick Haugh pointed out, you can't call read() twice on the same file object. Second, using regex to parse a simple key = value format is a bit overkill.
host, pingTimeout = None,None # Maybe intialize these to a default value
with open("settings.txt", "r") as f:
for line in f:
key,value = line.strip().split(" = ")
if key == 'host':
host = value
if key == 'pingTimeout':
pingTimeout = int(value)
print host, pingTimeout
Note that the expected input format would have no quotes for the example code above.
host = youtube.com
pingTimeout = 1
I tried this, it may help :
import re
filename = "<your text file with hostname>"
with open(filename) as f:
lines = f.read().splitlines()
for str in lines:
if re.search('host', str):
host, val = str.split('=')
val = val.replace("\"", "")
break
host = val
print host
f.close()

Test if string exists in file with Python

I'd like to add only servers currently doesn't exist at file
My current code :
f = open(filename,'a')
for server in cmo.getServers() :
print >>f, server.getListenAddress()
Thanks in advance
try this:
data = set( [i.strip() for i in open( filename, 'r' ).readlines()] )
for server in cmo.getServers() :
data.add( server.getListenAddress() )
open( filename, 'w' ).write('\n'.join(data))
Build a list of servers already present in the file:
present = [l.strip() for l in open(filename)]
(assuming the file format is just one server per line, no other symbols).
Then check if an address is in the list:
for server in cmo.getServers():
address = server.getListenAddress()
if address not in present:
print >>f, address
This assumes that the addresses you get from getServers() will not repeat.
If that's also possible, then build a set of them first:
new = set(server.getListenAddress() for server in cmo.getServers())
for address in new:
if address not in present:
print >>f, address

Categories