Python: How to print the local DNS Address ONLY? - python

when I type in nslookup in cmd I get this output:
Default Server: my server name.
Address: 192.168.2.1
I would like to use Python to output ONLY the DNS address. Just the number. How can I do that?
This is what I tried, but it opens up cmd again...
import os
print (os.system("nslookup"))
The output of print should be something like "192.168.2.1" ONLY.

Related

How to get the IP address of incoming connection in custom PAM module

I am using PAM authentication to authenticate with my linux server. I have created a view on my website through Apache2 where I can use python to manually validate each login through a web shell with facial recognition and two factor authentication. This is working, but I can't seem to recover the IP address of the incoming connection. I need a way to find the IP address of my connection to the server before SSH is connected, in the PAM module which is running Python. I would like to use bash for this.
I am trying to execute commands to recover the IP address, I tried using "who" and other commands to see incoming SSH connections to no avail. I also tried using "echo $PAM_RHOST" and "$SSH_CLIENT" and "$SSH_CONNECTION" with no success.
I ended up using the auth.log which seems to work perfectly. All I had to do was reverse the log and get the last IP. The below code also collects unique IPs in order of the last login.
`
output = run_command('sudo tail -500 /var/log/auth.log')
op = output.split('\n')
op.reverse()
output = '\n'.join(op)
def unique(thelist):
u = []
for i in thelist:
if i not in u: u.append(i)
return u
ips = unique(re.findall('Accepted publickey for user from ([\d]+\.[\d]+\.[\d]+\.[\d]+)', output))
ip = ips[0]
print(ip) # The last IP
`

Getting 127.0.1.1 instead of 192.168.1.* ip ubuntu python

I am new to python. I want to get the ipaddress of the system. I am connected in LAN. When i use the below code to get the ip, it shows 127.0.1.1 instead of 192.168.1.32. Why it is not showing the LAN ip. Then how can i get my LAN ip. Every tutorials shows this way only. I also checked via connecting with mobile hotspot. Eventhough, it shows the same.
import socket
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
print("Your Computer Name is:" + hostname)
print("Your Computer IP Address is:" + IPAddr)
Output:
Your Computer Name is:smackcoders
Your Computer IP Address is:127.0.1.1
Required Output:
Your Computer Name is:smackcoders
Your Computer IP Address is:192.168.1.32
I got this same problem with my raspi.
host_name = socket.gethostname()`
host_addr = socket.gethostbyname(host_name)
and now if i print host_addr, it will print 127.0.1.1.
So i foundthis: https://www.raspberrypi.org/forums/viewtopic.php?t=188615#p1187999
host_addr = socket.gethostbyname(host_name + ".local")
and it worked.
As per the above '/etc/hosts' file content, you have an IP address mapping with '127.0.1.1' to your hostname. This is causing the name resolution to get 127.0.1.1. You can try removing/commenting this line and rerun.
How can I get the IP address of eth0 in Python?
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print s.getsockname()[0]
This also worked for me:
gethostbyname(gethostname()+'.')
i get the same problem what your are facing. but I get the solution with help of my own idea, And don't worry it is simple to use.
if you familiar to linux you should heard the ifconfig command which return the informations about the network interfaces, and also you should understand about grep command which filter the lines which consist specified words
now just open the terminal and type
ifconfig | grep 255.255.255.0
and hit enter now you will get wlan inet address line alone like below
inet 192.168.43.248 netmask 255.255.255.0 broadcast 192.168.43.255
in your terminal
in your python script just insert
#!/usr/bin/env python
import subprocess
cmd = "ifconfig | grep 255.255.255.0"
inet = subprocess.check_output(cmd, shell = True)
inet = wlan.decode("utf-8")
inet = wlan.split(" ")
inet_addr = inet[inet.index("inet")+1]
print(inet_addr)
this script return your local ip address, this script works for me and I hope this will work for your linux machine
all the best
This solution works for me on Windows. If you're using Linux you could try this line of code instead:
IPAddr = socket.gethostbyname(socket.getfqdn())

Cannot console into new created Openstack instance

I installed Openstack Mitaka using Devstack on an Ubuntu virtual machine in Virtualbox. After installation, things seemed to be alright. Then I start a new Cirros instance, and it succeeded. However, when I tried to console this instance using ip nets exec xxxxxx ssh cirros#172.24.4.3 it returned ssh: connect to host 172.24.4.3 port 22: no route to host. Result for ip nets exec xxxxxx ping 172.24.4.3 is Destination Host Unreachable.
I checked the ip netsh, the result was like:
qrouter-xxxxxxx
qdhcp-xxxxxx
If I use ip nets exec qrouter-xxxxxx ip addr show , the result includes:
127.0.0.1, 10.0.0.1, 172.24.4.2, and another item with no ip address.
If I user ip nets exec qdhcp-xxxxxx ip addr show, the result includes:
127.0.0.1, 10.0.0.2
The instance is connected to public network as shown in Openstack Dashboard. And if I try to connect to the console in WebUI - Dashboard/Compute/Instances/xxxx/Console, there was an error shown on the page, saying:
Error response. Error code 404.Message: File not found.
Error code explanation: 404 = Nothing matches the given URI.
So how can I console into the instances created by Openstack? Is it something to do with the network configuration?
Thank you for your answers in advance.

Paramiko - How to tell which host the SSHClient is currently connected to?

I have a script that loops over a dozen hosts and executes several functions in each host. The functions take as a parameter the SSHClient() and then execute commands on it.
I could simply set some attribute on the SSHClient(), but before I do that, is there already a way to determine from an instance of SSHClient() which host is currently being connected to?
for host in hosts:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=USERNAME)
f1(ssh)
f2(ssh)
...
Using the ssh variable for the Client, as you've done, there is:
ssh.get_transport().getpeername()
Which will return a tuple of ('ip address', portnumber)
Will that be enough? Looking at the source for paramiko/client.py it doesn't seem to keep a record of the value of connect()'s hostname parameter, it looks up the address with socket.getaddrinfo and then passes the result on to the transport, which is what getpeername() is asking.
The following is probably what you are after...
stdin, stdout, stderr = ssh.exec_command('hostname')
hostname = stdout.read().decode("utf-8").strip('\n')
print(hostname)
How it works:
On any windows and linux, if you type hostname on any terminal, then you will get back the server name. We execute this cmd on the remote, get back the returned output and change it from byte to string format and finally take off trailing new line character.
This is how I solved the issue:
getpeername() returns an IP address, which is not very user friendly for a log message. So I wrapped it with socket.gethostbyaddr().
This returns the FQDN as a string:
socket.gethostbyaddr(ssh.get_transport().getpeername()[0])[0])
And this splits it to just the hostname itself:
socket.gethostbyaddr(ssh.get_transport().getpeername()[0])[0].split('.')[0])

python fabric get public ip address

Try to get public ip address of host with python fabric
def publicip():
ip = local("curl -s 'http://checkip.dyndns.org' | sed 's/.*Current IP Address: \([0-9\.]*\).*/\'\1/g\'")
print (red(ip))
Error:
Fatal error: local() encountered an error (return code 2) while executing 'curl -s 'http://checkip.dyndns.org' | sed 's/.*Current IP Address: \([0-9\.]*\).*/'/g''
Curl is probably not installed on the host you're running on. You don't need it anyway as you can do this easily in Python like this:
import urllib2
u = urllib2.urlopen('http://checkip.dyndns.org')
line = u.next()
print line.split("<")[6].split().pop()
I'm not sure what local() (executes an external command?) is, but using the requests library and re.search this is fairly simple:
import requests, re
r = requests.get('http://checkip.dyndns.org')
myip = re.search(r'\d+\.\d+\.\d+\.\d+', r.text).group()
It seems local() doesn't support multiple commands to be executed. You can however split the execution into:
def publicip():
ip = local("curl -s 'http://checkip.dyndns.org'", capture=True)
and then ip will contain the desired html:
'<html><head><title>Current IP Check</title></head><body>Current IP Address: 1.2.3.4</body></html>'
Which you can parse using regex, e.g.:
r = re.compile(r'.*\<body>Current IP Address:\s(.*)\</body>.*')
final_ip = r.match(ip).group(1)
A pure python implementation is
import requests
r = requests.get('http://ipof.in/txt')
myip = r.text
Thats it. Do check out http://ipof.in if you need further information beyond just IP address

Categories